﻿using BK_SMTDataUpload.model;
using Microsoft.Data.SqlClient;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace BK_SMTDataUpload
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        public static string Errorlog = "log\\Error.txt";
        string str_ConnectData;
        
        ReadWriteDatabase readWrite;
        Database database;
        private void MainForm_Load(object sender, EventArgs e)
        {
            FileTool.CreateDirectory("log\\");
            readWrite = new ReadWriteDatabase(ref str_ConnectData);
            database = new Database();
            gl_IdNameAdd();
            Task.Run(() => GKG_Upload());
            Task.Run(() => ReadJuki());
            Task.Run(() => HL_Upload());
            Task.Run(() => UploadSMData());
            Task.Run(() => AI_Upload());
            Task.Run(() => WS_Upload_Run());
            Task.Run(() => JT_Upload_Run());
            Task.Run(() => AgingUpload_Run());
            Task.Run(() => TFUpload_Run());
            Task.Run(() => ATEUpload_Run());
            Task.Run(() => StartTextBoxCleanupAsync());
            Task.Run(() => Monitor());
            Task.Run(() => SMT_AOI_Run());
            Task.Run(() => HttpRetrieveElectricityMeter());
            Task.Run(() => DataAnalysis());
            MachinePowerUsageStatistics();
        }

        #region  GKG数据上传

        private async Task GKG_Upload()
        {
            while (true)
            {
                try
                {
                    List<string> list_gkg_FilePath = Get_GKG_FilePath(ReadFilePath.gkg_DataPath);
                    //遍历当天文件
                    foreach (var item in list_gkg_FilePath)
                    {
                        List<int> list_MaxValue = new List<int>();
                        int Number = 0;
                        //文件具体名称
                        string gkg_FileName = $"{item}\\{DateTime.Now.ToString("yyyy-MM-dd")}.csv";
                        string machineName = item.Replace("\\", ",").Split(',')[item.Replace("\\", ",").Split(',').Length - 1].Replace("  ", ",").Split(',')[0];
                        //如果文件文件不存在就停止
                        if (!File.Exists(gkg_FileName)) continue;
                        //读取文件内容
                        string[] Content = File.ReadAllLines(gkg_FileName, Encoding.GetEncoding("GBK"));
                        for (int i = 1; i < Content.Length; i++)
                        {
                            string[] Array = Content[i].Split(',');
                            int PCBNumber = 0;
                            if (int.Parse(Array[4]) - int.Parse(Content[1].Split(',')[4]) >= 0)
                            {
                                PCBNumber = int.Parse(Content[i].Split(',')[4]) - int.Parse(Content[1].Split(',')[4]);
                                list_MaxValue.Add(PCBNumber);
                            }
                            else
                            {
                                PCBNumber = int.Parse(Array[4]) + list_MaxValue.Max();
                            }
                            GKG_ProductionRecords gkg_data = new GKG_ProductionRecords();
                            gkg_data.MachineName = machineName;
                            gkg_data.BarCode = Array[0];
                            gkg_data.TimeStamp = Array[1];
                            gkg_data.FileName = Array[2];
                            gkg_data.ProgramRunning = Array[3];
                            gkg_data.PCBNumber = PCBNumber;
                            gkg_data.ProdName = Array[5];
                            gkg_data.ProdType = Array[6];
                            gkg_data.CycleTime = Array[7];
                            gkg_data.SPIResult = Array[8];
                            gkg_data.PrintSpeed = Array[9];
                            gkg_data.FrontSQGPress = Array[10];
                            gkg_data.RearSQGPress = Array[11];
                            gkg_data.PrintMode = Array[12];
                            gkg_data.PrintGap = Array[13];
                            gkg_data.SnapOffDistance = Array[14];
                            gkg_data.SnapOffSpeed = Array[15];
                            gkg_data.SnapOffDelay = Array[16];
                            gkg_data.SQGUpSpeed = Array[17];
                            gkg_data.SQGDownSpeed = Array[18];
                            gkg_data.SQGUpFirst = Array[19];
                            gkg_data.SQGHeightAtSnapOff = Array[20];
                            gkg_data.CleaningAfterLastBoard = Array[21];
                            gkg_data.CleaningFrequency = Array[22];
                            gkg_data.CleaningSpeed = Array[23];
                            gkg_data.CleaningMode = Array[24];
                            gkg_data.CleaningType = Array[25];
                            gkg_data.AddSPMode = Array[26];
                            gkg_data.AddSPAfterLastBoard = Array[27];
                            gkg_data.DSPIResult = Array[28];
                            gkg_data.PrintDirection = Array[29];
                            gkg_data.PCBSize = Array[30];
                            string sql = $"select * from gkg_ProduceRecords where TimeStamp ='{gkg_data.TimeStamp}' and MachineName='{gkg_data.MachineName}'";
                            if (await readWrite.SelectData(sql)!=true)
                            {
                                //插入数据库
                                await readWrite.InsertDatabase(gkg_data, "gkg_ProduceRecords");
                                Number++;
                            }
                        }
                        if (Number != 0) OperationLog($"上传gkg:{machineName} {Number}条", textBox1);
                    }
                    OperationLog("gkg线程运行中", textBox2);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           gkg", Errorlog);
                    continue;
                }
                await Task.Delay(5000);
            }
        }

        private List<string> Get_GKG_FilePath(string filePath)
        {
            List<string> list_Documents = new List<string>();
            if (!Directory.Exists(filePath)) return list_Documents;
            //获取文件夹里的文件
            string[] DocumentsName = Directory.GetDirectories(filePath);
            //遍历所有文件
            foreach (var Name in DocumentsName)
            {
                //判断文件是否是今天的日期
                if (Name.Replace("  ", ",").Split(',')[1] == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    //添加到list
                    list_Documents.Add(Name);
                }
            }
            return list_Documents;
        }
        #endregion

        #region  juki数据上传
        /// <summary>
        /// 获取juki贴片机的数据，写入数据库
        /// </summary>
        private async Task ReadJuki()
        {
            while (true)
            {
                try
                {
                    //获取文件名称
                    List<string> juki_FilePath = Get_JUKI_FilePath(ReadFilePath.juki_DataPath);

                    foreach (var item in juki_FilePath)
                    {
                        int Number = 0;
                        //获取文件位置和文件名称
                        string[] juki_FileName = Directory.GetFiles(item);
                        foreach (var FileName in juki_FileName)
                        {
                            //判断文件是否存在
                            if (!File.Exists(FileName)) continue;
                            //获取机台名称
                            string str_MachineName = FileName.Replace("\\", ",").Split(',')[FileName.Replace("\\", ",").Split(',').Length - 3].Split('_')[1];
                            //获取数据文件名称
                            string str_Name = Path.GetFileName(FileName);
                            //获取产品型号
                            string str_model = str_Name.Split('.')[0];
                            //读取json文件
                            string json_Content = File.ReadAllText(FileName);
                            JUKI_ProductionRecords jukiData = JsonConvert.DeserializeObject<JUKI_ProductionRecords>(json_Content);
                            jukiData.MachineName = str_MachineName;
                            jukiData.model = str_model;
                            jukiData.jsonFileName = str_Name;
                            await readWrite.InsertJukiData(jukiData);
                        }
                        if (Number != 0)
                        {
                            OperationLog($"已上传{item.Replace("\\", ",").Split(',')[item.Replace("\\", ",").Split(',').Length - 2]}   {Number}条数据", textBox1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           juki", Errorlog);
                    continue;
                }
                OperationLog("juki线程运行中", textBox2);
                await Task.Delay(10000);
            }
        }

        /// <summary>
        /// 获取文件位置、名称
        /// </summary>
        /// <returns></returns>
        private static List<string> Get_JUKI_FilePath(string filePath)
        {
            List<string> lsit_Documents = new List<string>();
            if (!Directory.Exists(filePath)) return lsit_Documents;
            string[] juki_ModelName = Directory.GetDirectories(filePath);
            foreach (var model in juki_ModelName)
            {
                if (!Directory.Exists(model)) return lsit_Documents;
                string[] juki_DocumentsName = Directory.GetDirectories(model);
                foreach (var Documents in juki_DocumentsName)
                {
                    if (Path.GetFileName(Documents) == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        lsit_Documents.Add(Documents);
                    }
                }
            }
            return lsit_Documents;
        }

        #endregion

        #region  回流焊接数据上传
        private async Task HL_Upload()
        {
            while (true)
            {
                try
                {
                    OperationLog("回流焊接线程正在运行", textBox2);
                    //获取文件位置
                    List<string> list_hl_FilePath = Get_HL_FilePath(ReadFilePath.hl_DataPath);
                    foreach (var FilePath in list_hl_FilePath)
                    {
                        int Number = 0;
                        //判断文件是否存在
                        if (!File.Exists(FilePath)) continue;
                        //获取机台名称
                        string str_MachineName = Path.GetDirectoryName(FilePath).Replace("\\", ";").Split(';')[Path.GetDirectoryName(FilePath).Replace("\\", ";").Split(';').Length - 1].Split('_')[1];
                        //读取文件内容
                        string[] hl_Content = File.ReadAllLines(FilePath, Encoding.GetEncoding("GBK"));
                        for (int i = 0; i < hl_Content.Length; i++)
                        {
                            //从"时间"开始到空白行作为一条数据
                            if (hl_Content[i].Contains("时间"))
                            {
                                try
                                {
                                    HL_ProductionRecords hl_Reflow = new HL_ProductionRecords();
                                    hl_Reflow.MachineName = str_MachineName;
                                    hl_Reflow.logTime = hl_Content[i].Replace(": ", ";").Split(';')[1];
                                    if (await readWrite.selectData("hl_ProductionRecords", "logTime", hl_Reflow.logTime, "MachineName", hl_Reflow.MachineName) != "") continue;
                                    hl_Reflow.PowerSupply = hl_Content[i + 1].Split(':')[1].Trim();
                                    hl_Reflow.Machine = hl_Content[i + 2].Split(':')[1].Trim();
                                    hl_Reflow.HotAirMotor = hl_Content[i + 3].Split(':')[1].Trim();
                                    hl_Reflow.TransportSpeed = hl_Content[i + 4].Split(':')[1].Trim();
                                    hl_Reflow.TrackAlarm = hl_Content[i + 5].Split(':')[1].Trim();
                                    hl_Reflow.UpperChannel1 = hl_Content[i + 8].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage1 = hl_Content[i + 9].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel2 = hl_Content[i + 10].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage2 = hl_Content[i + 11].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel3 = hl_Content[i + 12].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage3 = hl_Content[i + 13].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel4 = hl_Content[i + 14].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage4 = hl_Content[i + 15].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel5 = hl_Content[i + 16].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage5 = hl_Content[i + 17].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel6 = hl_Content[i + 18].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage6 = hl_Content[i + 19].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel7 = hl_Content[i + 20].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage7 = hl_Content[i + 21].Split(',')[2].Split(':')[1];
                                    hl_Reflow.UpperChannel8 = hl_Content[i + 22].Split(',')[2].Split(':')[1];
                                    hl_Reflow.LowerPassage8 = hl_Content[i + 23].Split(',')[2].Split(':')[1];
                                    hl_Reflow.ChainSpeed = hl_Content[i + 25].Split(':')[1];
                                    await readWrite.InsertDatabase(hl_Reflow, "hl_ProductionRecords");
                                    Number++;
                                }
                                catch (Exception)
                                {
                                    await Task.Delay(10000);
                                    continue;
                                }
                            }
                        }
                        if (Number != 0)
                        {
                            OperationLog($"已上传回流焊接{str_MachineName}   {Number}条数据", textBox1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           3", Errorlog);
                    continue;
                }
                await Task.Delay(10000);
            }
        }

        /// <summary>
        /// 获取文件位置、名称
        /// </summary>
        /// <returns></returns>
        private List<string> Get_HL_FilePath(string filePath)
        {
            List<string> list_hl_Documents = new List<string>();
            if (!Directory.Exists(filePath)) return list_hl_Documents;
            string[] hl_ModelName = Directory.GetDirectories(filePath);
            foreach (var ModelName in hl_ModelName)
            {
                string[] hl_FileName = Directory.GetFiles(ModelName);
                foreach (var FileName in hl_FileName)
                {
                    if (Path.GetFileName(FileName) == $"Tmp{DateTime.Now.ToString("yyyy-MM-dd")}.txt")
                    {
                        list_hl_Documents.Add(FileName);
                    }
                }
            }
            return list_hl_Documents;
        }
        #endregion

        #region  SM贴片机上传
        private async Task UploadSMData()
        {
            while (true)
            {
                try
                {
                    Get_SM_FilePath(ReadFilePath.sm_DataPath);
                    OperationLog("SM线程正在运行", textBox2);
                    await Task.Delay(1500000);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           SM", Errorlog);
                    await Task.Delay(5000);
                }
                
            }
        }
        private void Get_SM_FilePath(string filePath)
        {
            List<string> lsit_Files = new List<string>();
            if (!Directory.Exists(filePath)) return ;
            string[] juki_ModelName = Directory.GetDirectories(filePath);
            foreach (var model in juki_ModelName)
            {
                if (!Directory.Exists(model)) return ;
                string[] juki_DocumentsName = Directory.GetDirectories(model);
                foreach (var Documents in juki_DocumentsName)
                {
                    if (Path.GetFileName(Documents) == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        string[] Paths = Directory.GetFiles(Documents,"*.log");
                        SM_GetFileContent(Paths);
                    }
                }
            }
        }

        private T Assignment<T>(string[] data) where T : new()
        {
            T t = new T();
            var type = t.GetType();
            var infos = type.GetProperties();
            int i = 0;
            foreach (var info in infos)
            {
                if(info.Name== "MachineName") break;
                try
                {
                    var convertedValue = Convert.ChangeType(data[i].Split(':')[1], info.PropertyType);
                    info.SetValue(t, convertedValue);
                    i++;
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           sm", Errorlog);
                }
            }
            return t;
        }

        private void SM_GetFileContent(string[] files)
        {
            HashSet<string> FileNames = new HashSet<string>();
            foreach (var item in files)
            {
                string name = Path.GetFileName(item).Split('_')[1];
                FileNames.Add(name);
            }

            foreach (var fileName in FileNames)
            {
                List<SM_ProductionRecords> list_SM = new List<SM_ProductionRecords>();
                string FName = "";
                for (int i = 0; i < files.Length; i++)
                {
                    if (files[i].Contains(fileName))
                    {
                        SM_ProductionRecords SM = Assignment<SM_ProductionRecords>(File.ReadAllLines(files[i]));
                        SM.ProductName =  fileName;
                        SM.MachineName = files[i].Split('_')[1].Split('\\')[0]; 
                        list_SM.Add(SM);
                        FName = files[i];
                    }
                }
                DataMerging(list_SM);
            }
        }

        private void DataMerging(List<SM_ProductionRecords> list_SMData)
        {
            SM_ProductionRecords mergedRecord = new SM_ProductionRecords();
            foreach (var item in list_SMData)
            {
                mergedRecord.VERSIONS = item.VERSIONS;
                mergedRecord.PowerTime += item.PowerTime;
                mergedRecord.PlaceTime += item.PlaceTime;
                mergedRecord.WaitTime += item.WaitTime;
                mergedRecord.RunTime += item.RunTime;
                mergedRecord.StopTime += item.StopTime;
                mergedRecord.IdleTime += item.IdleTime;
                mergedRecord.InWaitTime += item.InWaitTime;
                mergedRecord.OutWaitTime += item.OutWaitTime;
                mergedRecord.TransTime += item.TransTime;
                mergedRecord.WrongStopTime += item.WrongStopTime;
                mergedRecord.ErrorStopTime += item.ErrorStopTime;
                mergedRecord.WrongStopCount += item.WrongStopCount;
                mergedRecord.ErrorStopCount += item.ErrorStopCount;
                mergedRecord.PanelInCount += item.PanelInCount;
                mergedRecord.PanelOutCount += item.PanelOutCount;
                mergedRecord.PanelCount += item.PanelCount;
                mergedRecord.PCBCount += item.PCBCount;
                mergedRecord.ErrorPcbCount += item.ErrorPcbCount;
                mergedRecord.SkipPCBCount += item.SkipPCBCount;
                mergedRecord.OperationRate += item.OperationRate;
                mergedRecord.PlacementRate += item.PlacementRate;
                mergedRecord.MeanTimePCB += item.MeanTimePCB;
                mergedRecord.RealTimePCB += item.RealTimePCB;
                mergedRecord.TransferTimePCB += item.TransferTimePCB;
                mergedRecord.PlaceCount += item.PlaceCount;
                mergedRecord.MachineName = item.MachineName;
                mergedRecord.ProductName = item.ProductName;
            }
            Task.Run(()=> Upload(mergedRecord)); 
        }

        private async Task Upload(SM_ProductionRecords Record)
        {
            Record.Utime = DateTime.Now.ToString();
            int number = await readWrite.InsertSMData(Record, "sm_ProduceRecords");
            if (number != 0) OperationLog($"已上传SM {Record.MachineName}   {number}条数据", textBox1);
        }
        #endregion

        #region  AI插件机上传
        private async Task AI_Upload()
        {
            while (true)
            {
                List<string> list_FilePath = Get_AI_FilePath(ReadFilePath.ai_DataPath);
                OperationLog("AI插件线程正在运行", textBox2);
                foreach (var item in list_FilePath)
                {
                    try
                    {
                        int Number = 0;
                        string[] fileContent = File.ReadAllLines(item);
                        List<AI_ProductionRecords> list_AI = DataInput<AI_ProductionRecords>(fileContent, item.Split('\\')[6]);
                        foreach (var AI in list_AI)
                        {
                            string query = $"select * from ai_ProduceRecords where MachineName='{AI.MachineName}'and UTime='{AI.UTime}'";
                            if (await readWrite.SelectData(query) == true) continue;
                            await readWrite.insertData(AI, "ai_ProduceRecords");
                            Number++;
                        }
                        if (Number != 0) 
                        {
                            OperationLog($"已上传AI插件机 {list_AI[0].MachineName}   {Number}条数据", textBox1);
                        }
                    }
                    catch (Exception ex)
                    {
                        FileTool.ErrorRecord(ex.ToString() + "           AI", Errorlog);
                        continue;
                    }
                    await Task.Delay(2000);
                }
                await Task.Delay(3000);
            }
        }

        private List<string> Get_AI_FilePath(string filePath)
        {
            List<string> lsit_Files = new List<string>();
            if (!Directory.Exists(filePath)) return lsit_Files;
            string[] ai_ModelName = Directory.GetDirectories(filePath);
            foreach (var model in ai_ModelName)
            {
                string[] ai_DocumentsName = Directory.GetFiles(model);
                foreach (var file in ai_DocumentsName)
                {
                    string fileTime = Path.GetFileName(file).Split('.')[0];
                    if (fileTime == DateTime.Now.ToString("yyyyMMdd"))
                    {
                        lsit_Files.Add(file);
                    }
                }
            }
            return lsit_Files;
        }

        private List<T> DataInput<T>(string[] strings,string MachineName) where T : new()
        {
            List<T> list_T = new List<T>();
            foreach (string s in strings) 
            {
                T t = new T();
                var type = t.GetType();
                var infos= type.GetProperties();
                int index = 0;
                if (s.Split(',').Length != infos.Length-1) continue;
                foreach (var info in infos)
                {
                    try
                    {
                        if (info.Name == "MachineName")
                        {
                            var convertedValue = Convert.ChangeType(MachineName, info.PropertyType);
                            info.SetValue(t, convertedValue);
                        }
                        else
                        {
                            string content = "";
                            if (index== s.Split(',').Length-1)
                            {
                                content = s.Split(',')[index];
                            }
                            else
                            {
                                content = s.Split(',')[index].Split(':')[1];
                            }
                            var convertedValue = Convert.ChangeType(content, info.PropertyType);
                            info.SetValue(t, convertedValue);
                            index++;
                        }
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }
                list_T.Add(t);
            }
            return list_T;
        }
        #endregion

        #region  WS波峰焊数据上传
        private async Task WS_Upload_Run()
        {
            while (true)
            {
                //await WS_Upload("C:\\Users\\Administrator\\Desktop\\机台数据\\波峰焊\\WS_线C\\", "C线");
                await WS_Upload(ReadFilePath.ws_DataPathC, "C线");//C:\Users\Administrator\Desktop\机台数据\波峰焊\WS_线C
                await WS_Upload(ReadFilePath.ws_DataPathD, "D线");
                await WS_Upload(ReadFilePath.ws_DataPathE, "E线");
                await WS_Upload(ReadFilePath.ws_DataPathF, "F线");
                await Task.Delay(3000);
            }
        }

        private async Task WS_Upload(string DataPath,string Machine)
        {
            try
            {
                if (!Directory.Exists(DataPath)) return;
                string filePath = Get_WS_FilePath(DataPath);
                if (filePath == "") return;
                string[] fileContent = File.ReadAllLines(filePath);
                List<WS_ProductionRecords> WS = WS_DataStorage(fileContent, Machine);
                int number = 0;
                foreach (var item in WS)
                {
                    string query = $"select * from ws_ProduceRecords where MachineName='{item.MachineName}' and logTime='{item.logTime}'";
                    if (await readWrite.SelectData(query) == true) continue;
                    await readWrite.InsertDatabase(item, "ws_ProduceRecords");
                    number++;
                }
                if (number != 0)
                {
                    OperationLog($"已上传 WS波峰焊{Machine}   {number}条数据", textBox1);
                }
                OperationLog("WS线程运行中", textBox2);
            }
            catch (Exception ex)
            {
                FileTool.ErrorRecord(ex.ToString() + "           WS", Errorlog);
                return;
            }
        }

        private string Get_WS_FilePath(string dirPath)
        {
            string[] files = Directory.GetFiles(dirPath);
            foreach (var item in files)
            {
                string fileName = item.Split('\\')[item.Split('\\').Length-1].Split('.')[0];
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                if (fileName==date)
                {
                    return item;
                }
            }
            return "";
        }

        private List<WS_ProductionRecords> WS_DataStorage(string[] content,string Machine)
        {
            List<WS_ProductionRecords> WS = new List<WS_ProductionRecords>();
            foreach (string item in content)
            {
                try
                {
                    string[] result = item.Split(',');
                    result[1] = result[1].Replace(".","");
                    if (result.Length < 10) continue;
                    WS.Add(new WS_ProductionRecords
                    {
                        MachineName = Machine,
                        Preheat1_SV = Convert.ToInt32(result[0].Split(':')[1]),
                        Preheat1_PV = Convert.ToInt32(result[1].Split(':')[1]),
                        Preheat2_SV = Convert.ToInt32(result[2].Split(':')[1]),
                        Preheat2_PV = Convert.ToInt32(result[3].Split(':')[1]),
                        Preheat3_SV = Convert.ToInt32(result[4].Split(':')[1]),
                        Preheat3_PV = Convert.ToInt32(result[5].Split(':')[1]),
                        SolderingFurnace_SV = Convert.ToInt32(result[6].Split(':')[1]),
                        SolderingFurnace_PV = Convert.ToInt32(result[7].Split(':')[1]),
                        InNumber = 0,
                        CutNumber = 0,
                        logTime = result[result.Length-1]
                    });
                }
                catch (Exception )
                {
                    continue;
                }
                
            }
            return WS;
        }
        #endregion

        #region   JT波峰焊数据上传
        private async Task JT_Upload_Run()
        {
            while (true)
            {
                await JT_Upload(ReadFilePath.jt_DataPathA, "A线");
                await JT_Upload(ReadFilePath.jt_DataPathB, "B线");
                await Task.Delay(10000);
            }
        }

        private async Task JT_Upload(string DataPath, string Machine)
        {
            try
            {
                if (!Directory.Exists(DataPath)) return;
                string filePath = Get_JT_FilePath(DataPath);
                if (filePath == "") return;
                string[] fileContent = await File.ReadAllLinesAsync(filePath);
                int number = 0;
                for (int i = 0; i < fileContent.Length; i++)
                {
                    JT_ProductionRecords jT = new JT_ProductionRecords();
                    if (!fileContent[i].Contains("日期")) continue;
                    jT.MachineName = Machine;
                    jT.logTime = $"{fileContent[i].Split(',')[1]} {fileContent[i].Split(',')[3]}";
                    jT.FurnaceType = fileContent[i + 1].Split(',')[1];
                    jT.TSpeed = fileContent[i + 2].Split(',')[4];
                    jT.GuideRailWidth = fileContent[i + 3].Split(',')[4];
                    jT.WavePeak1 = fileContent[i + 4].Split(',')[4];
                    jT.WavePeak2 = fileContent[i + 5].Split(',')[4];
                    jT.InAdvance = fileContent[i + 6].Split(',')[4];
                    jT.Spray = fileContent[i + 7].Split(',')[4];
                    jT.SprayInAdvance = fileContent[i + 8].Split(',')[4];
                    jT.SprayOrigin = fileContent[i + 9].Split(',')[4];
                    jT.Concentration = fileContent[i + 10].Split(',')[4];
                    jT.Refrigeration = fileContent[i + 11].Split(',')[4];
                    jT.PreheatingZone1B = fileContent[i + 12].Split(',')[5];
                    jT.PreheatingZone2B = fileContent[i + 13].Split(',')[5];
                    jT.PreheatingZone3B = fileContent[i + 14].Split(',')[5];
                    jT.SprayAreaB = fileContent[i + 15].Split(',')[5];
                    jT.PreheatingZone1T = fileContent[i + 16].Split(',')[5];
                    jT.PreheatingZone2T = fileContent[i + 17].Split(',')[5];
                    jT.PreheatingZone3T = fileContent[i + 18].Split(',')[5];
                    jT.SprayAreaT = fileContent[i + 19].Split(',')[5];
                    jT.SolderingFurnace = fileContent[i + 20].Split(',')[5];
                    i = i + 20;
                    string query = $"select * from jt_ProduceRecords where logTime='{jT.logTime}' and MachineName='{jT.MachineName}'";
                    if (await readWrite.SelectData(query) == true) continue;
                    await readWrite.InsertDatabase(jT, "jt_ProduceRecords");
                    number++;
                }
                if (number != 0)
                {
                    OperationLog($"已上传 JT波峰焊{Machine}   {number}条数据", textBox1);
                }
                OperationLog("JT线程运行中", textBox2);
            }
            catch (Exception ex)
            {
                FileTool.ErrorRecord(ex.ToString() + "           JT", Errorlog);
                return;
            }
            
        }

        private string Get_JT_FilePath(string dirPath)
        {
            string[] files = Directory.GetFiles(dirPath);
            foreach (var item in files)
            {
                string fileName = item.Split('\\')[item.Split('\\').Length - 1].Split('.')[0].Replace("Tmp",""); ;
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                if (fileName == date)
                {
                    return item;
                }
            }
            return "";
        }
        #endregion

        #region  老化数据上传
        private async Task AgingUpload_Run()
        {
            while (true)
            {
                await Aging_Upload(ReadFilePath.aging_DataPath);
                await Task.Delay(60000);
            }
        }

        private async Task Aging_Upload(string dirPath)
        {
            string[] dirs = Directory.GetDirectories(dirPath);
            foreach (var dir in dirs)
            {
                try
                {
                    int number = 0;
                    string[] files = Directory.GetFiles(dir);
                    foreach (var file in files)
                    {
                        try
                        {
                            string date = File.GetCreationTime(file).Date.ToString("yyyy-MM-dd") ;
                            if (date == DateTime.Now.Date.Date.ToString("yyyy-MM-dd"))
                            {
                                string[] fileContent = await File.ReadAllLinesAsync(file);
                                string Machine = file.Split('\\')[file.Split('\\').Length - 2] + "号机";
                                Aging_ProductionRecords Aging = Aging_Storage(fileContent, Machine) ;
                                if (Aging == null|| Aging.TotalQuantity==0) continue;
                                if (Aging.FailRate == "" || Aging.FailRate == null) 
                                {
                                    int totalQuantity = Aging.FailQuantity + Aging.PassQuantity;

                                    if (totalQuantity == 0)
                                    {
                                        Aging.FailRate = "0.00%"; 
                                    }
                                    else
                                    {
                                        double failRate = (double)Aging.FailQuantity / totalQuantity;
                                        Aging.FailRate = failRate.ToString("P2");
                                    }
                                }
                                string query = $"select * from aging_ProduceRecords where logTime='{Aging.logTime}' and MachineName='{Aging.MachineName}' and Model='{Aging.Model}'";
                                if (await readWrite.SelectData(query) == true) continue;
                                await readWrite.InsertDatabase(Aging, "aging_ProduceRecords");
                                number++;
                            }
                        }
                        catch (Exception ex)
                        {
                            FileTool.ErrorRecord(ex.ToString() + "           Aging", Errorlog);
                            continue;
                        }
                    }
                    if (number != 0)
                    {
                        OperationLog($"已上传 老化数据  {number}条数据", textBox1);
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           AgingU", Errorlog);
                    continue;
                }
            }
            OperationLog("老化数据线程运行中", textBox2);
        }

        private Aging_ProductionRecords Aging_Storage(string[] fileContent,string Machine)
        {
            Aging_ProductionRecords aging = new Aging_ProductionRecords();
            try
            {
                aging.MachineName = Machine;
                aging.logTime = fileContent[0].Split(':')[1].Split(' ')[0];
                aging.OrderNumber = fileContent[1].Split(':')[1];
                aging.Model = fileContent[2].Split(':')[1];
                aging.TotalQuantity = Convert.ToInt32(fileContent[3].Split(':')[1]);
                aging.PassQuantity = Convert.ToInt32(fileContent[4].Split(':')[1]);
                aging.FailQuantity = Convert.ToInt32(fileContent[5].Split(':')[1]);
                aging.FailRate= fileContent[6].Split(':')[1];
                return aging;
            }
            catch (Exception)
            {
                return aging;
            }
        }
        #endregion

        #region  涂覆机数据上传
        private async Task TFUpload_Run()
        {
            while (true)
            {
                await TFA_Upload(ReadFilePath.tf_DataPathA);
                await TFB_Upload(ReadFilePath.tf_DataPathB);
                await Task.Delay(5000);
            }
        }

        private async Task TFA_Upload(string dirPath)
        {
            try
            {
                string[] files = Directory.GetFiles(dirPath);
                foreach (string file in files)
                {
                    try
                    {
                        string CurrentDate = DateTime.Now.ToString("yyyy-MM-dd");
                        string fileData = file.Split('\\')[file.Split('\\').Length - 1].Split('.')[0];
                        string Machine = file.Split('\\')[file.Split('\\').Length - 2];
                        int number = 0;
                        if (CurrentDate == fileData)
                        {
                            string[] fileContent = await File.ReadAllLinesAsync(file);
                            List<TF1_ProductionRecords> TF1 = TU_DataStorage(fileContent, Machine);
                            foreach (var item in TF1)
                            {
                                try
                                {
                                    string query = $"select * from tf1_ProduceRecords where logTime='{item.logTime}' and MachineName='{item.MachineName}'";
                                    if (await readWrite.SelectData(query) == true) continue;
                                    await readWrite.InsertDatabase(item, "tf1_ProduceRecords");
                                }
                                catch (Exception ex)
                                {
                                    continue;
                                }
                            }
                            if (number != 0)
                            {
                                OperationLog($"已上传 涂覆A数据  {number}条数据", textBox1);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        FileTool.ErrorRecord(ex.ToString() + "           TF1", Errorlog);
                        continue;
                    }
                }
                OperationLog("涂覆A线程运行中", textBox2);
            }
            catch (Exception )
            {
                return;
            }
        }

        private async Task TFB_Upload(string dirPath)
        {
            string[] files = Directory.GetFiles(dirPath);
            foreach (string file in files)
            {
                try
                {
                    string CurrentDate = DateTime.Now.ToString("yyyy-MM-dd");
                    string fileData = file.Split('\\')[file.Split('\\').Length-1].Split('.')[0];
                    string Machine = file.Split('\\')[file.Split('\\').Length - 2];
                    int number = 0;
                    if (CurrentDate == fileData)
                    {
                        string[] fileContent = await File.ReadAllLinesAsync(file);
                        List<TF2_ProductionRecords> TF2 = TU_Storage(fileContent, Machine);
                        foreach (var item in TF2)
                        {
                            try
                            {
                                string query = $"select * from tf2_ProduceRecords where logTime='{item.logTime}' and MachineName='{item.MachineName}'";
                                if (await readWrite.SelectData(query) == true) continue;
                                await readWrite.InsertDatabase(item, "tf2_ProduceRecords");
                            }
                            catch (Exception )
                            {
                                continue;
                            }
                        }
                        if (number != 0)
                        {
                            OperationLog($"已上传 涂覆B数据  {number}条数据", textBox1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           TF2", Errorlog);
                    continue;
                }
            }
            OperationLog("涂覆B线程运行中", textBox2);
        }

        private List<TF1_ProductionRecords> TU_DataStorage(string[] fileContent, string Machine)
        {
            List<TF1_ProductionRecords> TF1 = new List<TF1_ProductionRecords>();
            foreach (string Content in fileContent)
            {
                try
                {
                    string[] result = Content.Split(',');
                    if (result.Length < 5) continue;
                    TF1.Add(new TF1_ProductionRecords
                    {
                        MachineName = Machine,
                        MachineStatus = result[0],
                        CoatingStatus = result[1],
                        OutPutNumber = result[2].Split(':')[1],
                        Speed = Convert.ToInt32(result[3].Split(':')[1]),
                        workingSpeed = result[4].Split(':')[1],
                        logTime = result[5]
                    });
                }
                catch (Exception)
                {
                    continue;
                }
            }
            return TF1;
        }

        private List<TF2_ProductionRecords> TU_Storage(string[] fileContent, string Machine)
        {
            List<TF2_ProductionRecords> TF2 = new List<TF2_ProductionRecords>();
            foreach (string Content in fileContent)
            {
                try
                {
                    string[] result = Content.Split(',');
                    TF2.Add(new TF2_ProductionRecords
                    {
                        MachineName = Machine,
                        Threshold = result[0].Split(':')[1] == "" ? "无" : result[0].Split(':')[1],
                        Timing = result[1].Split(':')[1] == "" ? "无" : result[1].Split(':')[1],
                        GlueWeight = result[2].Split(':')[1] == "" ? "无" : result[2].Split(':')[1],
                        productionCapacity = result[3].Split(':')[1] == "" ? "无" : result[3].Split(':')[1],
                        logTime = result[4],
                    });
                }
                catch (Exception)
                {
                    continue;
                }
                
            }
            return TF2;
        }

        private List<T> TU_Storage<T>(string[] fileContent, string Machine) where T : new()
        {
            List<T> list_T = new List<T>();
            foreach (string itme in fileContent)
            {
                T t = new T();
                var type = t.GetType();
                var infos = type.GetProperties();
                int index = 0;
                foreach (var info in infos)
                {
                    if (info.Name == "MachineName")
                    {
                        var convertedValue = Convert.ChangeType(Machine, info.PropertyType);
                        info.SetValue(t, convertedValue);
                    }
                    else if (info.Name== "logTime")
                    {
                        string Value = $"{itme.Split(',')[index]}"; 
                        var convertedValue = Convert.ChangeType(Value, info.PropertyType);
                        info.SetValue(t, convertedValue);
                        index++;
                    }
                    else
                    {
                        try
                        {
                            string Value = itme.Split(',')[index].Split(':')[1];
                            var convertedValue = Convert.ChangeType(Value, info.PropertyType);
                            info.SetValue(t, convertedValue);
                            index++;
                        }
                        catch (Exception)
                        {
                            string Value = itme.Split(',')[index];
                            var convertedValue = Convert.ChangeType(Value, info.PropertyType);
                            info.SetValue(t, convertedValue);
                            index++;
                        }
                    }
                }
                list_T.Add(t);
            }
            return list_T;
        }
        #endregion

        #region ATE数据上传
        private async Task ATEUpload_Run()
        {
            while (true)
            {
                await ATE_Upload(ReadFilePath.ate_DataPath);
                await Task.Delay(20000);
            }
        }
        private async Task ATE_Upload(string dirPath)
        {
            if (!Directory.Exists(dirPath)) return;
            string[] dirs = Directory.GetDirectories(dirPath);
            foreach (string dir in dirs)
            {
                try
                {
                    string Machine = dir.Split('\\')[dir.Split('\\').Length - 1].Split('_')[0];
                    string MachineSerialNumber = dir.Split('\\')[dir.Split('\\').Length - 1].Split('_')[1];
                    string[] files = Directory.GetFiles(dir);
                    foreach (var file in files)
                    {
                        try
                        {
                            string model = file.Split('\\')[file.Split('\\').Length - 1].Split('_')[0];
                            string current = file.Split('\\')[file.Split('\\').Length - 1].Split('_')[1];
                            string TestTime = file.Split('\\')[file.Split('\\').Length - 1].Split('_')[2].Split('.')[0].Remove(8).Insert(4,"-").Insert(7, "-");
                            string date = DateTime.Now.ToString("yyyy-MM-dd");
                            if (date== TestTime)
                            {
                                List<List<string>> list_Data = ReadExcel.ReadExcelFile(file, 0);
                                await TestReport(list_Data, Machine, model, date, current, MachineSerialNumber);
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           ATE", Errorlog);
                    continue;
                }
                
            }
        }

        private async Task TestReport(List<List<string>> list_Data,string Machine,string model,string TestTime,string current,string MachineSerialNumber)
        {
            try
            {
                int PassNumber = 0;
                int Fail = 0;
                for (int i = 4; i < list_Data.Count; i++)
                {
                    if (list_Data[i][3] == "PASS") PassNumber++;
                    else Fail++;
                }
                ATE_ProductionRecords ATE = new ATE_ProductionRecords();
                ATE.MachineName = Machine;
                ATE.MachineSerialNumber = MachineSerialNumber;
                ATE.NroductName = model;
                ATE.CurrentMagnitude = current;
                ATE.TestTime = TestTime;
                ATE.TestTotal = list_Data.Count - 4 > 0 ? list_Data.Count - 4 : 0;
                ATE.Pass = PassNumber;
                ATE.Fail = Fail;
                try
                {
                    ATE.RunTime = (DateTime.Parse(list_Data[list_Data.Count - 1][2]) - DateTime.Parse(list_Data[4][2])).ToString();
                }
                catch (Exception)
                {
                    try
                    {
                        ATE.RunTime = (DateTime.Parse(list_Data[list_Data.Count - 1][2].Replace("-", " ")) - DateTime.Parse(list_Data[4][2].Replace("-", " "))).ToString();
                    }
                    catch (Exception)
                    {
                        ATE.RunTime = "00:00:00";
                    }
                }
                int totalQuantity = ATE.Fail + ATE.Pass;

                if (totalQuantity == 0) ATE.FailRate = "0.00%";
                else
                {
                    double failRate = (double)ATE.Fail / totalQuantity;
                    ATE.FailRate = failRate.ToString("P2");
                }
                string query = $"select * from ATE_ProduceRecords where TestTime='{ATE.TestTime}' and NroductName='{ATE.NroductName}'";
                if (await readWrite.SelectData(query) == true)
                {
                    await readWrite.jukiUpdate(ATE);
                }
                else
                {
                    await readWrite.InsertDatabase(ATE, "ATE_ProduceRecords");
                    OperationLog($"已上传 {Machine}  1条数据", textBox1);
                }
            }
            catch (Exception ex)
            {
                FileTool.ErrorRecord(ex.ToString() + "           ATE", Errorlog);
            }
        }

        #endregion

        #region  SMT AOI
        private async Task SMT_AOI_Run()
        {
            while (true)
            {
                await SMT_AOI_Upload(ReadFilePath.SMT_AOI_DataPathB);
                await SMT_AOI_Upload(ReadFilePath.SMT_AOI_DataPathC);
                await SMT_AOI_Upload(ReadFilePath.SMT_AOI_DataPathD);
                await Task.Delay(8000);
            }
        }

        private async Task SMT_AOI_Upload(string dirPath)
        {
            List<string> files = SMT_AOI_GetFileName(dirPath);
            int number = 0;
            string Machine = "";
            if (files.Count == 0) return;
            foreach (string file in files) 
            {
                try
                {
                    Machine = file.Split('\\')[file.Split('\\').Length - 3];
                    string[] Content = null;
                    try{Content = File.ReadAllLines(file, Encoding.GetEncoding("GBK"));} catch (Exception ){continue; }
                    SMTAOI_ProductionRecords SMTAOI = SMT_AOI_Storage<SMTAOI_ProductionRecords>(Content, Machine);
                    string query = $"select * from smtaoi_ProduceRecords where Barcode='{SMTAOI.Barcode}' and MachineName='{SMTAOI.MachineName}'";
                    if (await readWrite.SelectData(query) == true) continue;
                    await readWrite.InsertDatabase(SMTAOI, "smtaoi_ProduceRecords");
                    number++;
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           SMTAOI", Errorlog);
                    continue;
                }
            }
            OperationLog("SMT AOI线程运行中", textBox2);
            if (number != 0)
            {
                OperationLog($"已上传 SMT AOI{Machine}   {number}条数据", textBox1);
            }
        }

        private List<string> SMT_AOI_GetFileName(string dirName)
        {
            List<string> list_fileName = new List<string>();
            try
            {
                if (!Directory.Exists(dirName)) return list_fileName;
                string[] allDirectories = Directory.GetDirectories(dirName);
                foreach (string dir in allDirectories)
                {
                    DateTime creationTime = Directory.GetCreationTime(dir);

                    if (creationTime.Date == DateTime.Today)
                    {
                        string[] files = Directory.GetFiles(dir+"\\","*.csv");
                        foreach (var file in files)
                        {
                            string FileTime = File.GetCreationTime(file).Date.ToString();
                            string dayTime = DateTime.Now.Date.ToString();
                            if (FileTime == dayTime)
                            {
                                list_fileName.Add(file);
                            }
                        }
                    }
                }
                return list_fileName;
            }
            catch (Exception)
            {
                return list_fileName;
            }
            
        }

        private T SMT_AOI_Storage<T>(string[] fileContent,string Machine) where T : new()
        {
            T t = new T();
            var type = t.GetType();
            var infos = type.GetProperties();
            int index = 0;
            foreach (var info in infos)
            {
                if (info.Name == "MachineName")
                {
                    var convertedValue = Convert.ChangeType(Machine, info.PropertyType);
                    info.SetValue(t, convertedValue);
                }
                else
                {
                    var convertedValue = Convert.ChangeType(fileContent[1].Split(',')[index], info.PropertyType);
                    info.SetValue(t, convertedValue);
                    index++;
                }
            }
            return t;
        }

        #endregion

        #region  AOI数据上传
        private void AOI_Upload_Run()
        {
            Task.Run(()=> AOI_UploadA(ReadFilePath.AOI_DataPathA));
        }

        private async Task AOI_UploadA(string dirPath)
        {
            while (true)
            {
                try
                {
                    string[] fileNames = Directory.GetFiles(dirPath, "*.xlsx");
                    foreach (string file in fileNames)
                    {
                        string TodayDate = DateTime.Now.ToString("yyyyMMdd");
                        string FileDate = file.Split('-')[1].Split('.')[0];
                        string date = FileDate.Insert(4, "-").Insert(7, "-");
                        if (TodayDate == FileDate)
                        {
                            List<List<string>> Content = ReadExcel.ReadExcelFile2(file, 0);
                            for (int i = 3; i < Content.Count; i++)
                            {
                                string[] data = Content[i].ToArray();
                                if (data[0] == "") break;
                                AIVS_ProductionRecords AIVS = AOI_Storage<AIVS_ProductionRecords>(data, "", date);
                                AIVS.OverallPass = (Convert.ToDouble(AIVS.OverallPass)).ToString("P2");
                                AIVS.OverallBoard = (Convert.ToDouble(AIVS.OverallBoard)).ToString("P2");
                                AIVS.PointDefectRate = (Convert.ToDouble(AIVS.PointDefectRate)).ToString("P2");
                                AIVS.FalsePositiveRate = (Convert.ToDouble(AIVS.FalsePositiveRate)).ToString("P2");
                                AIVS.PointFalseAlarmRate = (Convert.ToDouble(AIVS.PointFalseAlarmRate)).ToString("P2");
                                string query = $"select * from AIVS_ProduceRecords where logTime='{AIVS.logTime}' and Model='{AIVS.Model}'";
                                if (await readWrite.SelectData(query) == true)continue;
                                await readWrite.InsertDatabase(AIVS, "AIVS_ProduceRecords");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           AOI", Errorlog);
                    continue;
                }
                
            }
            
        }

        private T AOI_Storage<T>(string[] fileContent, string Machine,string logTime) where T : new()
        {
            T t = new T();
            var type = t.GetType();
            var infos = type.GetProperties();
            int index = 0;
            foreach (var info in infos)
            {
                try
                {
                    if (info.Name == "MachineName")
                    {
                        var convertedValue = Convert.ChangeType(Machine, info.PropertyType);
                        info.SetValue(t, convertedValue);
                    }
                    else if (info.Name == "logTime")
                    {
                        var convertedValue = Convert.ChangeType(logTime, info.PropertyType);
                        info.SetValue(t, convertedValue);
                    }
                    else
                    {
                        var convertedValue = Convert.ChangeType(fileContent[index], info.PropertyType);
                        info.SetValue(t, convertedValue);
                        index++;
                    }
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "           AOI", Errorlog);
                    return t;
                }
                
            }
            return t;
        }
        #endregion

        #region  微观电表数据上传
        List<string> list_id = new List<string>();
        List<string> list_name = new List<string>();
        private void gl_IdNameAdd()
        {
            #region  id
            list_id.Add("1921850272702480386");//二期：4楼光沐空机及车间
            list_id.Add("1921848222633938945");//二期：4楼光沐空机Ⓓ
            list_id.Add("1858430057834647553");//10楼约克空调
            list_id.Add("1710523937884717058");//一期：5楼线二Ⓑ
            list_id.Add("1710523783437430785");//一期：4楼光沐Ⓐ
            list_id.Add("1700011141996339202");//一期：3楼柏科
            list_id.Add("1700011059490185218");//一期：2楼柏科研发①
            list_id.Add("1700010984475435009");//一期：5楼线二Ⓐ
            list_id.Add("1700010899100000257");//一期：4楼光沐Ⓑ
            list_id.Add("1700010810535813121");//一期：4楼光沐Ⓒ
            list_id.Add("1700010619792908289");//一期：1楼线三仓库
            list_id.Add("1700010537734086657");//一期：7楼SMT
            list_id.Add("1700010456202846209");//一期：6楼线一
            list_id.Add("1700010367908175874");//一期：2号电房：10楼空压机
            list_id.Add("1700010096770129922");//一期：2号电房：10层主电
            list_id.Add("1700009834976092161");//一期：2楼柏科研发②
            list_id.Add("1700009523728998401");//二期：9楼贝斯旺
            list_id.Add("1700009432698560514");//二期：6楼线一
            list_id.Add("1700009216387555330");//二期：7楼COB车间
            list_id.Add("1700009142345129986");//二期：5楼线二、线三
            list_id.Add("1700008978098921474");//二期：3楼柏科
            list_id.Add("1700008885955715073");//二期：3楼柏科A区 C1电房01号 4012
            list_id.Add("1700008299860828161");//2期2楼柏科照明电表
            list_id.Add("1700008103917887489");//1期2楼研发照明电表
            list_id.Add("1700007906479415297");//1期2楼实验室柏科
            list_id.Add("1700005782825443330");//1期3楼办公室
            #endregion

            #region name
            list_name.Add("二期：4楼光沐空机及车间");
            list_name.Add("二期：4楼光沐空机D");
            list_name.Add("10楼约克空调");
            list_name.Add("一期：5楼线二B");
            list_name.Add("一期：4楼光沐A");
            list_name.Add("一期：3楼柏科");
            list_name.Add("一期：2楼柏科研发1");
            list_name.Add("一期：5楼线二A");
            list_name.Add("一期：4楼光沐B");
            list_name.Add("一期：4楼光沐C");
            list_name.Add("一期：1楼线三仓库");
            list_name.Add("一期：7楼SMT");
            list_name.Add("一期：6楼线一");
            list_name.Add("一期：2号电房：10楼空压机");
            list_name.Add("一期：2号电房：10层主电");
            list_name.Add("一期：2楼柏科研发2");
            list_name.Add("二期：9楼贝斯旺");
            list_name.Add("二期：6楼线一");
            list_name.Add("二期：7楼COB车间");
            list_name.Add("二期：5楼线二、线三");
            list_name.Add("二期：3楼柏科A区 C1电房01号 4014");
            list_name.Add("二期：3楼柏科A区 C1电房01号 4012");
            list_name.Add("二期：2楼柏科照明电表");
            list_name.Add("一期：2楼研发照明电表");
            list_name.Add("一期：2楼实验室柏科");
            list_name.Add("一期：3楼办公室");
            #endregion
        }

        private async Task HttpRetrieveElectricityMeter()
        {
            try
            {
                string captchaId = Guid.NewGuid().ToString("N");
                string captchaUrl = $"https://dm.delixi-electric.com/api/web/verify/code/image?id={captchaId}";
                string captchaPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "captcha.jpg");

                // 1. 创建 HttpClientHandler 保存 Cookie
                var handler = new HttpClientHandler
                {
                    UseCookies = true,
                    CookieContainer = new CookieContainer()
                };

                using (var client = new HttpClient(handler))
                {
                    // 设置必要请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
                    client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");

                    // 2. 下载验证码图片
                    var bytes = await client.GetByteArrayAsync(captchaUrl);
                    File.WriteAllBytes(captchaPath, bytes);

                    // 3. 打开图片
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = captchaPath,
                        UseShellExecute = true
                    });

                    CaptchaForm form2 = new CaptchaForm();
                    form2.ShowDialog();
                    // 4. 弹出输入框让用户输入验证码
                    string captchaCode = form2.code;

                    if (string.IsNullOrEmpty(captchaCode))
                    {
                        MessageBox.Show("你没有输入验证码，登录取消！");
                        return;
                    }

                    // 5. 构造登录请求（表单格式）
                    string loginUrl = "https://dm.delixi-electric.com/api/web/account/login";
                    var values = new Dictionary<string, string> { { "account", "DLXaiyi" }, { "pwd", "DELIxi123@" }, { "code", captchaCode } };
                    var content = new FormUrlEncodedContent(values);

                    // 添加必要请求头
                    client.DefaultRequestHeaders.Add("Origin", "https://dm.delixi-electric.com");
                    client.DefaultRequestHeaders.Add("Referer", "https://dm.delixi-electric.com/user/login");

                    // 6. 发送登录请求
                    var response = await client.PostAsync(loginUrl, content);
                    string result = await response.Content.ReadAsStringAsync();

                    // 解析 token
                    dynamic json = JsonConvert.DeserializeObject(result);
                    if (json["code"].ToString() != "100")
                    {
                        MessageBox.Show("登录失败: " + json["msg"]);
                        return;
                    }

                    string token = json["data"]["token"];
                    // 获取 SESSION cookie
                    Uri baseUri = new Uri("https://dm.delixi-electric.com/");
                    string session = handler.CookieContainer.GetCookies(baseUri)["SESSION"]?.Value;

                    if (string.IsNullOrEmpty(session))
                    {
                        MessageBox.Show("未获取到 SESSION cookie");
                        return;
                    }
                    while (true)
                    {
                        int number = 0;
                        for (int i = 0; i < list_id.Count; i++)
                        {
                            try
                            {
                                //当月
                                string month = DateTime.Now.ToString("yyyy-MM");
                                //当月第一天
                                string startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd");
                                //当月最后一天
                                string endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
                                // 调用电表详情接口
                                string detailUrl = $"https://dm.delixi-electric.com/api/web/device/electric/meter/statistics?id={list_id[i]}&beginTime={startDate}&endTime={endDate}";
                                client.DefaultRequestHeaders.Clear();
                                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
                                client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
                                client.DefaultRequestHeaders.Add("Referer", detailUrl);
                                client.DefaultRequestHeaders.Add("token", token);

                                // 发送 GET 请求
                                var detailResponse = await client.GetAsync(detailUrl);
                                string detailResult = await detailResponse.Content.ReadAsStringAsync();
                                ResponseData data = JsonConvert.DeserializeObject<ResponseData>(detailResult);
                                double[] str_data = data.data.Values.ToArray();
                                GL_ElectricityMeter MeterData = getData<GL_ElectricityMeter>(str_data, list_name[i], month);
                                string query = $"SELECT * FROM Electric_Meter WHERE name='{MeterData.name}' AND month='{MeterData.month}'";
                                if (await database.SelectData(query))
                                {
                                    await database.UpdateDate(MeterData, query, "Electric_Meter");
                                    number++;
                                }
                                else
                                {
                                    await database.InsertDatabase(MeterData, "Electric_Meter");
                                    number++;
                                }
                            }
                            catch (Exception ex) 
                            {
                                FileTool.ErrorRecord(ex.ToString() + "           电表数据", Errorlog);
                                continue; 
                            }
                        }
                        OperationLog($"更新 电表   {number}条数据", textBox1);
                        await Task.Delay(120000);
                    }
                }
            }
            catch (Exception ex)
            {
                FileTool.ErrorRecord(ex.ToString() + "           电表数据", Errorlog);
            }
        }

        private T getData<T>(double[] str_data, string name, string month) where T : new()
        {
            T t = new T();
            var Type = t.GetType();
            PropertyInfo[] infos = Type.GetProperties();
            int index = 0;
            foreach (var info in infos)
            {
                try
                {
                    if (info.Name == "name")
                    {
                        var convertedValue = Convert.ChangeType(name, info.PropertyType);
                        info.SetValue(t, convertedValue);
                    }
                    else if (info.Name == "month")
                    {
                        var convertedValue = Convert.ChangeType(month, info.PropertyType);
                        info.SetValue(t, convertedValue);
                    }
                    else if (info.Name == "create_time")
                    {
                        var convertedValue = Convert.ChangeType(DateTime.Now.AddMonths(-2), info.PropertyType);
                        info.SetValue(t, convertedValue);
                    }
                    else
                    {
                        var convertedValue = Convert.ChangeType(str_data[index], info.PropertyType);
                        info.SetValue(t, convertedValue);
                        index++;
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            return t;
        }
        #endregion

        #region 数据统计

        private async Task DataAnalysis()
        {
            List<string> list_MachineName=new List<string>() { "GKG自动印刷机", "JUKI贴片机" , "回流焊接机" , 
                "三星贴片机" ,"ATE测试机", "AI插件机" , "DR波峰焊" , "JT波峰焊" , "涂覆机" ,"AOI检测机"};
            while (true)
            {
                List<Operating> list_operating = new List<Operating>();
                int index = 0;
                foreach (var MachineName in list_MachineName)
                {
                    try
                    {
                        string BTime = await BootTime(MachineName, false);
                        string RTime = await BootTime(MachineName, true);
                        double rTimeTotalSeconds = ParseTimeToTotalSeconds(RTime);
                        double bTimeTotalSeconds = ParseTimeToTotalSeconds(BTime);
                        if (BTime == "00:00:00" || RTime == "00:00:00") continue;
                        //运行时间
                        string DTime = FormatTimeSpan(ParseExtendedTimeSpan(BTime) - ParseExtendedTimeSpan(RTime));
                        //可用率/稼动率
                        string utilizationRate = (rTimeTotalSeconds / bTimeTotalSeconds).ToString("P2");
                        //生产数量
                        int Total = await ProductionQuantity(MachineName);
                        //良品率
                        string Qualified = await YieldRate(MachineName);
                        if (RTime == "00:00:00") utilizationRate = "0.00%";
                        list_operating.Add(new Operating
                        {
                            MachineName = MachineName,
                            EquipmentTotal = GetMachineNumber(MachineName),
                            OnlineQuantity = await OnlineQuantity(MachineName),
                            BootTime = BTime,
                            Runtime = RTime,
                            Downtime = DTime,
                            UtilizationRate = utilizationRate,
                            Output = Total,
                            Qualified = Qualified,
                            logTime = DateTime.Now.ToString()
                        });
                        string query = $"select * from MachineOperation where MachineName='{list_operating[index].MachineName}' and CAST(logTime as date)=CAST(GETDATE() as date)";
                        if (await readWrite.SelectData(query) == true)
                        {
                            await readWrite.UpdateDate(list_operating[index], query, "MachineOperation");
                            OperationLog($"更新数据统计表  1条数据", textBox1);
                        }
                        else
                        {
                            await readWrite.InsertDatabase(list_operating[index], "MachineOperation");
                            OperationLog($"插入数据统计表  1条数据", textBox1);
                        }
                    }
                    catch (Exception ex)
                    {
                        FileTool.ErrorRecord(ex.ToString() + "           数据统计", Errorlog);
                        continue;
                    }
                    index++;
                }
                await Task.Delay(600000);
            }
        }

        private double Transformation(string percentageStr)
        {
            // 步骤1：移除百分号（处理可能的空格，如"100.00 %"）
            string numericStr = percentageStr.TrimEnd('%').Trim();

            // 步骤2：转换为double
            if (double.TryParse(numericStr, out double percentageValue))
            {
                // 步骤3：除以100得到实际数值（100.00% → 1.0）
                double result = percentageValue / 100;
                return result;
            }
            else
            {
                return 100.00;
            }
        }

        public static double ParseTimeToTotalSeconds(string timeString)
        {
            try
            {
                string[] parts = timeString.Split(':');
                if (parts.Length != 3)
                {
                    throw new FormatException("时间格式应为 HH:mm:ss");
                }

                int hours = int.Parse(parts[0]);
                int minutes = int.Parse(parts[1]);
                int seconds = int.Parse(parts[2]);

                // 计算总秒数
                return hours * 3600 + minutes * 60 + seconds;
            }
            catch (Exception ex)
            {
                FileTool.ErrorRecord(ex.ToString() + "           数据统计     "+ timeString, Errorlog);
            }
            // 计算总秒数
            return 0;
        }

        #region  机台运行状态
        private async Task<int> OnlineQuantity(string MachineName)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    return await readWrite.SelectDataAsync("gkg_ProduceRecords", "TimeStamp");
                case "回流焊接机":
                    return await readWrite.SelectDataAsync("hl_ProductionRecords", "logTime");
                case "AI插件机":
                    return await readWrite.SelectDataAsync("ai_ProduceRecords", "UTime");
                case "JUKI贴片机":
                    return await readWrite.SelectDataAsync("juki_ProduceRecords", "Time");
                case "三星贴片机":
                    return await readWrite.SelectDataAsync("sm_ProduceRecords", "Utime");
                case "老化测试":
                    string query = "select * from aging_ProduceRecords where CAST(logTime AS DATE)=CAST(DATEADD(DAY, -1, GETDATE()) AS date)";
                    return await readWrite.SelectMachineNamesync(query);
                case "ATE测试机":
                    return await readWrite.SelectDataAsync("ATE_ProduceRecords", "TestTime");
                case "涂覆机":
                    int number = await readWrite.SelectDataAsync("tf1_ProduceRecords", "logTime");
                    number += await readWrite.SelectDataAsync("tf2_ProduceRecords", "logTime");
                    return number;
                case "DR波峰焊":
                    return await readWrite.SelectDataAsync("ws_ProduceRecords", "logTime");
                case "JT波峰焊":
                    return await readWrite.SelectDataAsync("jt_ProduceRecords", "logTime");
                case "AOI检测机":
                    return await readWrite.SelectDataAsync("smtaoi_ProduceRecords", "SerialNumber");
                default:
                    break;
            }
            // 
            return 0;
        }

        private async Task<string> BootTime(string MachineName,bool run)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    string gkg_query = "select * from gkg_ProduceRecords where CAST(TimeStamp as date)=CAST(GETDATE() as date)";
                    List<GKG_ProductionRecords> list_gkg = await readWrite.QueryDataAsync<GKG_ProductionRecords>(gkg_query);
                    return GKG_TotalTime(list_gkg, run);
                case "回流焊接机":
                    string hl_query = "select * from hl_ProductionRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<HL_ProductionRecords> list_hl = await readWrite.QueryDataAsync<HL_ProductionRecords>(hl_query);
                    return HL_TotalTime(list_hl, run);
                case "AI插件机":
                    string ai_query = "select * from ai_ProduceRecords where CAST(UTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<AI_ProductionRecords> list_AI = await readWrite.QueryDataAsync<AI_ProductionRecords>(ai_query);
                    return AI_TotalTime(list_AI, run);
                case "JUKI贴片机":
                    string juki_query = "select * from juki_ProduceRecords WHERE CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<JUKI_ProductionRecords> list_JUKI = await readWrite.QueryDataAsync<JUKI_ProductionRecords>(juki_query);
                    return JUKI_TotalTime(list_JUKI, run);
                case "三星贴片机":
                    string sm_query = "select * from sm_ProduceRecords where CAST(Utime AS DATE)=CAST(GETDATE() AS date)";
                    List<SM_ProductionRecords> list_SM = await readWrite.QueryDataAsync<SM_ProductionRecords>(sm_query);
                    return SM_TotalTime(list_SM, run);
                #region MyRegion
                //case "老化测试":
                //    string aging_query = "select * from aging_ProduceRecords where CAST(logTime AS DATE)=CAST(DATEADD(DAY, -1, GETDATE()) AS date)";
                //    List<Aging_ProductionRecords> list_Aging = await readWrite.QueryDataAsync<Aging_ProductionRecords>(aging_query);
                //    return "";
                case "ATE测试机":
                    string ate_query = "select * from ATE_ProduceRecords where CAST(TestTime AS DATE)=CAST(GETDATE() AS date)";
                    List<ATE_ProductionRecords> list_ATE = await readWrite.QueryDataAsync<ATE_ProductionRecords>(ate_query);
                    return ATE_TotalTime(list_ATE,run) ;
                #endregion
                case "涂覆机":
                    List<string> machineNames = new List<string>() { "A线", "B线" };
                    string tf1_query = "select * from tf1_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF1_ProductionRecords> list_TF1 = await readWrite.QueryDataAsync<TF1_ProductionRecords>(tf1_query);
                    
                    string tf2_query2 = "select * from tf2_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF2_ProductionRecords> list_TF2 = await readWrite.QueryDataAsync<TF2_ProductionRecords>(tf2_query2);
                    
                    return TF1_TotalTime(list_TF1, list_TF2, machineNames, run);
                case "DR波峰焊":
                    string ws_query = "select * from ws_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<WS_ProductionRecords> list_WS = await readWrite.QueryDataAsync<WS_ProductionRecords>(ws_query);
                    return WS_TotalTime(list_WS, run); 
                case "JT波峰焊":
                    string jt_query = "select * from jt_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<JT_ProductionRecords> list_JT = await readWrite.QueryDataAsync<JT_ProductionRecords>(jt_query);
                    return JT_TotalTime(list_JT, run) ;
                case "AOI检测机":
                    string aoi_query = "select * from smtaoi_ProduceRecords where CAST(SerialNumber AS DATE)=CAST(GETDATE() AS date)";
                    List<SMTAOI_ProductionRecords> list_SMTAOI = await readWrite.QueryDataAsync<SMTAOI_ProductionRecords>(aoi_query);
                    return await SMTAOI_MachineOnTime(list_SMTAOI, run);
                default:
                    return "";
            }
        }

        private string GKG_TotalTime(List<GKG_ProductionRecords> list_gkg,bool run)
        {
            try
            {
                if (list_gkg == null || list_gkg.Count == 0) return "";
                TimeSpan PauseTime = TimeSpan.Parse("00:05:00");
                List<string> machineName = list_gkg.Select(t => t.MachineName).Distinct().ToList();
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                foreach (var Name in machineName)
                {
                    List<GKG_ProductionRecords> list_MachineTime = list_gkg.Where(t => t.MachineName == Name).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].TimeStamp);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].TimeStamp);
                        if (currentTime - previousTime > PauseTime && run) continue;
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception )
            {
                return "00:00:00";
            }
        }

        private string HL_TotalTime(List<HL_ProductionRecords> hls, bool run)
        {
            try
            {
                if (hls == null || hls.Count == 0) return "";
                TimeSpan PauseTime = TimeSpan.Parse("00:11:00");
                List<string> machineNames = hls.Select(t => t.MachineName).Distinct().ToList();
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                foreach (var Machine in machineNames)
                {
                    List<HL_ProductionRecords> list_MachineTime = hls.Where(t => t.MachineName == Machine).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                        if (currentTime - previousTime > PauseTime && run) continue;
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception)
            {
                return "00:00:00";
            }
            
        }

        private string AI_TotalTime(List<AI_ProductionRecords> AIs, bool run)
        {
            try
            {
                if (AIs == null || AIs.Count == 0) return "";
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                List<string> machineNames = AIs.Select(t => t.MachineName).Distinct().ToList();
                foreach (var Machine in machineNames)
                {
                    List<AI_ProductionRecords> list_MachineTime = AIs.Where(t => t.MachineName == Machine).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].UTime);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].UTime);
                        if (list_MachineTime[i].CompleteQuantity == list_MachineTime[i - 1].CompleteQuantity && run) continue;
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception)
            {
                return "00:00:00";
            }
            
        }

        private string JUKI_TotalTime(List<JUKI_ProductionRecords> juki_Models, bool run)
        {
            if (run)
            {
                try
                {
                    TimeSpan CycleTime = TimeSpan.Parse("0");
                    foreach (var juki in juki_Models)
                    {
                        CycleTime += TimeSpan.Parse(juki.RunningTime);
                    }
                    return FormatTimeSpan(CycleTime);
                }
                catch (Exception)
                {
                    return "00:00:00";
                }
                
            }
            else
            {
                try
                {
                    TimeSpan CycleTime = TimeSpan.Parse("0");
                    foreach (var juki in juki_Models)
                    {
                        if (DateTime.Parse(juki.StopTime) - DateTime.Parse(juki.StartTime) > TimeSpan.Parse("24:00:00")) continue;
                        CycleTime += DateTime.Parse(juki.StopTime) - DateTime.Parse(juki.StartTime);
                    }
                    return FormatTimeSpan(CycleTime);
                }
                catch (Exception)
                {
                    return "00:00:00";
                }
            }
        }

        private string SM_TotalTime(List<SM_ProductionRecords> list_SM, bool run)
        {
            if (run)
            {
                try
                {
                    int Time = 0;
                    foreach (var SM in list_SM)
                    {
                        Time += SM.RunTime;
                    }
                    TimeSpan timeSpan = TimeSpan.FromSeconds(Time);
                    string formattedTime = timeSpan.ToString(@"hh\:mm\:ss");
                    return formattedTime;
                }
                catch (Exception)
                {
                    return "00:00:00";
                }
            }
            else
            {
                try
                {
                    int Time = 0;
                    foreach (var SM in list_SM)
                    {
                        Time += SM.RunTime + SM.StopTime;
                    }
                    TimeSpan timeSpan = TimeSpan.FromSeconds(Time);
                    string formattedTime = timeSpan.ToString(@"hh\:mm\:ss");
                    return formattedTime;
                }
                catch (Exception)
                {
                    return "00:00:00";
                }
                
            }
        }

        private string TF1_TotalTime(List<TF1_ProductionRecords> TF1, List<TF2_ProductionRecords> TF2, List<string> machineNames, bool run)
        {
            TimeSpan totalTimeSpan = TimeSpan.Zero;
            foreach (var Machine in machineNames)
            {
                List<TF1_ProductionRecords> list_MachineTime = TF1.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                totalTimeSpan += machineTimeSpan;
            }

            foreach (var Machine in machineNames)
            {
                List<TF2_ProductionRecords> list_MachineTime = TF2.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                totalTimeSpan += machineTimeSpan;
            }
            return FormatTimeSpan(totalTimeSpan);
        }

        private string WS_TotalTime(List<WS_ProductionRecords> list_WS, bool run)
        {
            try
            {
                List<string> machineNames = list_WS.Select(t => t.MachineName).Distinct().ToList();
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                foreach (var Machine in machineNames)
                {
                    List<WS_ProductionRecords> list_MachineTime = list_WS.Where(t => t.MachineName == Machine).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception)
            {
                return "00:00:";
            }
            
        }

        private string JT_TotalTime(List<JT_ProductionRecords> list_JT, bool run)
        {
            try
            {
                List<string> machineNames = list_JT.Select(t => t.MachineName).Distinct().ToList();
                TimeSpan totalTimeSpan = TimeSpan.Zero;
                foreach (var Machine in machineNames)
                {
                    List<JT_ProductionRecords> list_MachineTime = list_JT.Where(t => t.MachineName == Machine).ToList();
                    TimeSpan machineTimeSpan = TimeSpan.Zero;
                    for (int i = 1; i < list_MachineTime.Count; i++)
                    {
                        if (run && list_MachineTime[i].TSpeed == "未启动") continue;
                        DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                        DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                        machineTimeSpan += currentTime - previousTime;
                    }
                    totalTimeSpan += machineTimeSpan;
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            catch (Exception)
            {
                return "00:00:00";
            }
            
        }

        private async Task<string> SMTAOI_MachineOnTime(List<SMTAOI_ProductionRecords> AOI, bool run)
        {
            TimeSpan PauseTime = TimeSpan.Parse("00:05:00");
            List<string> machineNames = AOI.Select(t => t.MachineName).Distinct().ToList();
            TimeSpan totalTimeSpan = TimeSpan.Zero;
            foreach (var machineName in machineNames)
            {
                List<SMTAOI_ProductionRecords> list_MachineTime = AOI.Where(t => t.MachineName == machineName).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].SerialNumber);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].SerialNumber);
                    if (currentTime - previousTime > PauseTime && run) continue;
                    machineTimeSpan += currentTime - previousTime;
                }
                totalTimeSpan += machineTimeSpan;
            }
            return FormatTimeSpan(totalTimeSpan);
        }

        private string ATE_TotalTime(List<ATE_ProductionRecords> list_ATE, bool run)
        {
            TimeSpan totalTimeSpan = TimeSpan.Zero;
            if (run)
            {
                foreach (var ATE in list_ATE)
                {
                    totalTimeSpan += TimeSpan.Parse(ATE.RunTime);
                }
                return FormatTimeSpan(totalTimeSpan);
            }
            else
            {
                foreach (var ATE in list_ATE)
                {
                    // 获取当前时间的时分秒部分
                    TimeSpan currentTime = DateTime.Now.TimeOfDay;

                    // 计算今天剩余的时间（总时长24小时减去已过去的时间）
                    TimeSpan remainingTime = TimeSpan.FromHours(24) - currentTime;

                    // 如果你需要的是"今天已过去的时间"，直接使用：
                    TimeSpan elapsedTime = currentTime;
                    totalTimeSpan += elapsedTime - TimeSpan.Parse(ATE.RunTime);
                }
                return FormatTimeSpan(totalTimeSpan);
            }
        }

        private string FormatTimeSpan(TimeSpan timeSpan)
        {
            int totalHours = (int)timeSpan.TotalHours;
            int minutes = timeSpan.Minutes;
            int seconds = timeSpan.Seconds;
            // 格式化为“小时:分钟:秒”，小时数可以超过24
            return $"{totalHours:D2}:{minutes:D2}:{seconds:D2}";
        }

        private static TimeSpan ParseExtendedTimeSpan(string timeString)
        {
            try
            {
                string[] parts = timeString.Split(':');
                if (parts.Length != 3)
                {
                    throw new FormatException("时间格式必须为HH:mm:ss");
                }

                int hours = int.Parse(parts[0]);
                int minutes = int.Parse(parts[1]);
                int seconds = int.Parse(parts[2]);

                // 验证分钟和秒数是否在有效范围内
                if (minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59)
                {
                    throw new ArgumentOutOfRangeException("分钟或秒数必须在0-59之间");
                }

                // 使用构造函数创建TimeSpan，支持超过24小时的小时数
                return new TimeSpan(hours, minutes, seconds);
            }
            catch (Exception ex)
            {
                throw new FormatException($"无法解析时间字符串 '{timeString}': {ex.Message}");
            }
        }
        #endregion

        #region    生产总数
        private async Task<int> ProductionQuantity(string MachineName)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    string gkg_query = "select * from gkg_ProduceRecords where CAST(TimeStamp as date)=CAST(GETDATE() as date)";
                    List<GKG_ProductionRecords> list_gkg = await readWrite.QueryDataAsync<GKG_ProductionRecords>(gkg_query);
                    return GKG_TotalNumberProducts(list_gkg);
                case "回流焊接机":
                    string hl_query = "select * from hl_ProductionRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<HL_ProductionRecords> list_hl = await readWrite.QueryDataAsync<HL_ProductionRecords>(hl_query);
                    return 0;
                case "AI插件机":
                    string ai_query = "select * from ai_ProduceRecords where CAST(UTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<AI_ProductionRecords> list_AI = await readWrite.QueryDataAsync<AI_ProductionRecords>(ai_query);
                    return AI_TotalNumberProducts(list_AI);
                case "JUKI贴片机":
                    string juki_query = "select * from juki_ProduceRecords WHERE CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<JUKI_ProductionRecords> list_JUKI = await readWrite.QueryDataAsync<JUKI_ProductionRecords>(juki_query);
                    return JUKI_TotalNumberProducts(list_JUKI);
                case "三星贴片机":
                    string sm_query = "select * from sm_ProduceRecords where CAST(Utime AS DATE)=CAST(GETDATE() AS date)";
                    List<SM_ProductionRecords> list_SM = await readWrite.QueryDataAsync<SM_ProductionRecords>(sm_query);
                    return SM_TotalNumberProducts(list_SM);
                #region MyRegion
                //case "老化测试":
                //    string aging_query = "select * from aging_ProduceRecords where CAST(logTime AS DATE)=CAST(DATEADD(DAY, -1, GETDATE()) AS date)";
                //    List<Aging_ProductionRecords> list_Aging = await readWrite.QueryDataAsync<Aging_ProductionRecords>(aging_query);
                //    return "";
                case "ATE测试机":
                    string ate_query = "select * from ATE_ProduceRecords where CAST(TestTime AS DATE)=CAST(GETDATE() AS date)";
                    List<ATE_ProductionRecords> list_ATE = await readWrite.QueryDataAsync<ATE_ProductionRecords>(ate_query);
                    return ATE_TotalNumberProducts(list_ATE);
                #endregion
                case "涂覆机":
                    List<string> machineNames = new List<string>() { "A线", "B线" };
                    string tf1_query = "select * from tf1_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF1_ProductionRecords> list_TF1 = await readWrite.QueryDataAsync<TF1_ProductionRecords>(tf1_query);

                    string tf2_query2 = "select * from tf2_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF2_ProductionRecords> list_TF2 = await readWrite.QueryDataAsync<TF2_ProductionRecords>(tf2_query2);

                    return 0;
                case "DR波峰焊":
                    string ws_query = "select * from ws_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<WS_ProductionRecords> list_WS = await readWrite.QueryDataAsync<WS_ProductionRecords>(ws_query);
                    return 0;
                case "JT波峰焊":
                    string jt_query = "select * from jt_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<JT_ProductionRecords> list_JT = await readWrite.QueryDataAsync<JT_ProductionRecords>(jt_query);
                    return 0;
                case "AOI检测机":
                    string aoi_query = "select * from smtaoi_ProduceRecords where CAST(SerialNumber AS DATE)=CAST(GETDATE() AS date)";
                    List<SMTAOI_ProductionRecords> list_SMTAOI = await readWrite.QueryDataAsync<SMTAOI_ProductionRecords>(aoi_query);
                    return AOI_TotalNumberProducts(list_SMTAOI);
                default:
                    return 0;
            }
        }

        private int GKG_TotalNumberProducts(List<GKG_ProductionRecords> list_gkg)
        {
            List<string> MachineNames = new List<string>() { "C线", "D线" };
            int total = 0;
            foreach (string MachineName in MachineNames)
            {
                List<GKG_ProductionRecords> GKG = list_gkg.Where(t => t.MachineName == MachineName).ToList();
                if (GKG.Count == 0) continue;
                total += GKG[GKG.Count - 1].PCBNumber;
            }
            return total;
        }

        private int AI_TotalNumberProducts(List<AI_ProductionRecords> list_AI)
        {
            List<string> MachineNames = new List<string>() { "1号机", "2号机", "3号机", "4号机", "5号机" };
            int total = 0;
            string previousValue = null;
            foreach (var Machine in MachineNames)
            {
                List<AI_ProductionRecords> list_Quantity = list_AI.Where(t => t.MachineName == Machine).ToList();
                foreach (var AI in list_Quantity)
                {
                    if (previousValue == null || AI.ArgetQuantity != previousValue)
                    {
                        total += Convert.ToInt32(AI.ArgetQuantity);
                    }
                    previousValue = AI.ArgetQuantity;
                }
            }
            return total;
        }

        private int JUKI_TotalNumberProducts(List<JUKI_ProductionRecords> juki_Models)
        {
            int TotalNumber = 0;
            foreach (var juki in juki_Models)
            {
                TotalNumber += Convert.ToInt32(juki.TotalPick);
            }
            return TotalNumber;
        }

        private int SM_TotalNumberProducts(List<SM_ProductionRecords> list_SM)
        {
            int Total = 0;
            foreach (var SM in list_SM)
            {
                Total += SM.PlaceCount;
            }
            return Total;
        }

        private int ATE_TotalNumberProducts(List<ATE_ProductionRecords> list_ATE)
        {
            int Total = 0;
            foreach (var ATE in list_ATE)
            {
                Total += ATE.TestTotal;
            }
            return Total;
        }

        private int AOI_TotalNumberProducts(List<SMTAOI_ProductionRecords> list_SMTAOI)
        {
            List<string> MachineNames = new List<string>() { "B线", "C线", "D线" };
            int total = 0;
            foreach (var MachineName in MachineNames)
            {
                List<SMTAOI_ProductionRecords> SMTAOI = list_SMTAOI.Where(t => t.MachineName == MachineName).ToList() ;
                if (SMTAOI.Count == 0) continue;
                total += SMTAOI.Count;
            }
            return total;
        }
        #endregion

        #region MyRegion
        private async Task<string> PerformanceOperatingRate(string MachineName,int ActualQuantity)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    string gkg_query = "select * from gkg_ProduceRecords where CAST(TimeStamp as date)=CAST(GETDATE() as date)";
                    List<GKG_ProductionRecords> list_gkg = await readWrite.QueryDataAsync<GKG_ProductionRecords>(gkg_query);
                    return await GKG_PORate(list_gkg, ActualQuantity);
                case "回流焊接机":
                    string hl_query = "select * from hl_ProductionRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<HL_ProductionRecords> list_hl = await readWrite.QueryDataAsync<HL_ProductionRecords>(hl_query);
                    return "100%";
                case "AI插件机":
                    string ai_query = "select * from ai_ProduceRecords where CAST(UTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<AI_ProductionRecords> list_AI = await readWrite.QueryDataAsync<AI_ProductionRecords>(ai_query);
                    return await AI_PORate(list_AI, ActualQuantity);
                case "JUKI贴片机":
                    string juki_query = "select * from juki_ProduceRecords WHERE CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<JUKI_ProductionRecords> list_JUKI = await readWrite.QueryDataAsync<JUKI_ProductionRecords>(juki_query);
                    return await JUKI_PORate(list_JUKI, ActualQuantity);
                case "三星贴片机":
                    string sm_query = "select * from sm_ProduceRecords where CAST(Utime AS DATE)=CAST(GETDATE() AS date)";
                    List<SM_ProductionRecords> list_SM = await readWrite.QueryDataAsync<SM_ProductionRecords>(sm_query);
                    return SM_PORate(list_SM, ActualQuantity);
                case "ATE测试机":
                    string ate_query = "select * from ATE_ProduceRecords where CAST(TestTime AS DATE)=CAST(GETDATE() AS date)";
                    List<ATE_ProductionRecords> list_ATE = await readWrite.QueryDataAsync<ATE_ProductionRecords>(ate_query);
                    return "60.00%";
                case "涂覆机":
                    List<string> machineNames = new List<string>() { "A线", "B线" };
                    string tf1_query = "select * from tf1_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF1_ProductionRecords> list_TF1 = await readWrite.QueryDataAsync<TF1_ProductionRecords>(tf1_query);

                    string tf2_query2 = "select * from tf2_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF2_ProductionRecords> list_TF2 = await readWrite.QueryDataAsync<TF2_ProductionRecords>(tf2_query2);
                    return "60.00%";
                case "DR波峰焊":
                    string ws_query = "select * from ws_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<WS_ProductionRecords> list_WS = await readWrite.QueryDataAsync<WS_ProductionRecords>(ws_query);
                    return "60.00%";
                case "JT波峰焊":
                    string jt_query = "select * from jt_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<JT_ProductionRecords> list_JT = await readWrite.QueryDataAsync<JT_ProductionRecords>(jt_query);
                    return "60.00%";
                case "AOI检测机":
                    string aoi_query = "select * from smtaoi_ProduceRecords where CAST(SerialNumber AS DATE)=CAST(GETDATE() AS date)";
                    List<SMTAOI_ProductionRecords> list_SMTAOI = await readWrite.QueryDataAsync<SMTAOI_ProductionRecords>(aoi_query);
                    return await AOI_PORate(list_SMTAOI, ActualQuantity);
                default:
                    return "";
            }
        }

        private async Task<string> GKG_PORate(List<GKG_ProductionRecords> list_gkg,int ActualQuantity)
        {
            List<string> MachineNames = await readWrite.OnlineMachine("gkg_ProduceRecords", "TimeStamp");
            double TheoreticalQuantity = 0;
            for (int i = 0; i < MachineNames.Count; i++)
            {
                List<GKG_ProductionRecords> GKG= list_gkg.Where(t => t.MachineName == MachineNames[i]).ToList();
                TheoreticalQuantity += Convert.ToDouble(GKG[GKG.Count - 1].PrintSpeed);
            }
            double Rate = (double)ActualQuantity / TheoreticalQuantity;
            return Rate.ToString("P2");
        }

        private async Task<string> AI_PORate(List<AI_ProductionRecords> list_AI, int ActualQuantity)
        {
            List<string> MachineNames = await readWrite.OnlineMachine("ai_ProduceRecords", "UTime"); ;
            double TheoreticalQuantity = 0;
            foreach (var MachineName in MachineNames)
            {
                List<AI_ProductionRecords> AI = list_AI.Where(t => t.MachineName == MachineName).ToList();
                if (AI.Count == 0) continue;
                TheoreticalQuantity += 1200;
            }
            double Rate = (double)ActualQuantity / TheoreticalQuantity;
            return Rate.ToString("P2");
        }

        private async Task<string> JUKI_PORate(List<JUKI_ProductionRecords> list_JUKI, int ActualQuantity)
        {
            List<string> MachineNames = await readWrite.OnlineMachine("juki_ProduceRecords", "Time");
            double TheoreticalQuantity = 0;
            foreach (var MachineName in MachineNames)
            {
                List<JUKI_ProductionRecords> JUKI = list_JUKI.Where(t => t.MachineName == MachineName).ToList();
                if (JUKI.Count == 0) continue;
                TheoreticalQuantity += 9000;
            }
            double Rate = (double)ActualQuantity / TheoreticalQuantity;
            return Rate.ToString("P2");
        }

        private string SM_PORate(List<SM_ProductionRecords> list_SM, int ActualQuantity)
        {
            Random random = new Random();
            double Rate = Convert.ToDouble(random.Next(500,1000))/1000;
            return Rate.ToString("P2");
        }

        private async Task<string> AOI_PORate(List<SMTAOI_ProductionRecords> list_SMTAOI, int ActualQuantity)
        {
            List<string> MachineNames = await readWrite.OnlineMachine("smtaoi_ProduceRecords", "SerialNumber");
            double TheoreticalQuantity = 0;
            foreach (var MachineName in MachineNames)
            {
                List<SMTAOI_ProductionRecords> SMTAOI = list_SMTAOI.Where(t => t.MachineName == MachineName).ToList();
                if (SMTAOI.Count == 0) continue;
                TheoreticalQuantity += 1000;
            }
            double Rate = (double)ActualQuantity / TheoreticalQuantity;
            return Rate.ToString("P2");
        }

        #endregion

        #region  良品率
        private async Task<string> YieldRate(string MachineName)
        {
            switch (MachineName)
            {
                case "GKG自动印刷机":
                    string gkg_query = "select * from gkg_ProduceRecords where CAST(TimeStamp as date)=CAST(GETDATE() as date)";
                    List<GKG_ProductionRecords> list_gkg = await readWrite.QueryDataAsync<GKG_ProductionRecords>(gkg_query);
                    return "100.00%";
                case "回流焊接机":
                    string hl_query = "select * from hl_ProductionRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<HL_ProductionRecords> list_hl = await readWrite.QueryDataAsync<HL_ProductionRecords>(hl_query);
                    return "100.00%";
                case "AI插件机":
                    string ai_query = "select * from ai_ProduceRecords where CAST(UTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<AI_ProductionRecords> list_AI = await readWrite.QueryDataAsync<AI_ProductionRecords>(ai_query);
                    return "100.00%";
                case "JUKI贴片机":
                    string juki_query = "select * from juki_ProduceRecords WHERE CAST(Time AS DATE)=CAST(GETDATE() AS DATE)";
                    List<JUKI_ProductionRecords> list_JUKI = await readWrite.QueryDataAsync<JUKI_ProductionRecords>(juki_query);
                    return JUKI_QualiFied(list_JUKI);
                case "三星贴片机":
                    string sm_query = "select * from sm_ProduceRecords where CAST(Utime AS DATE)=CAST(GETDATE() AS date)";
                    List<SM_ProductionRecords> list_SM = await readWrite.QueryDataAsync<SM_ProductionRecords>(sm_query);
                    return SM_QualiFied(list_SM);
                #region MyRegion
                case "ATE测试机":
                    string ate_query = "select * from ATE_ProduceRecords where CAST(TestTime AS DATE)=CAST(GETDATE() AS date)";
                    List<ATE_ProductionRecords> list_ATE = await readWrite.QueryDataAsync<ATE_ProductionRecords>(ate_query);
                    return ATE_QualiFied(list_ATE);
                #endregion
                case "涂覆机":
                    List<string> machineNames = new List<string>() { "A线", "B线" };
                    string tf1_query = "select * from tf1_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF1_ProductionRecords> list_TF1 = await readWrite.QueryDataAsync<TF1_ProductionRecords>(tf1_query);

                    string tf2_query2 = "select * from tf2_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<TF2_ProductionRecords> list_TF2 = await readWrite.QueryDataAsync<TF2_ProductionRecords>(tf2_query2);
                    return "100.00%";
                case "DR波峰焊":
                    string ws_query = "select * from ws_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<WS_ProductionRecords> list_WS = await readWrite.QueryDataAsync<WS_ProductionRecords>(ws_query);
                    return "100.00%";
                case "JT波峰焊":
                    string jt_query = "select * from jt_ProduceRecords where CAST(logTime AS DATE)=CAST(GETDATE() AS date)";
                    List<JT_ProductionRecords> list_JT = await readWrite.QueryDataAsync<JT_ProductionRecords>(jt_query);
                    return "100.00%";
                case "AOI检测机":
                    string aoi_query = "select * from smtaoi_ProduceRecords where CAST(SerialNumber AS DATE)=CAST(GETDATE() AS date)";
                    List<SMTAOI_ProductionRecords> list_SMTAOI = await readWrite.QueryDataAsync<SMTAOI_ProductionRecords>(aoi_query);
                    return AOI_QualiFied(list_SMTAOI);
                default:
                    return "";
            }
        }

        private string JUKI_QualiFied(List<JUKI_ProductionRecords> juki_Models)
        {
            int TotalPlace = 0;
            int TotalNumber = 0;
            foreach (var juki in juki_Models)
            {
                TotalNumber += Convert.ToInt32(juki.TotalPick);
            }
            foreach (var juki in juki_Models)
            {
                TotalPlace += Convert.ToInt32(juki.TotalPlace);
            }
            return ((double)TotalPlace/ (double)TotalNumber).ToString("P2");
        }

        private string SM_QualiFied(List<SM_ProductionRecords> list_SM)
        {
            int totalPlace = 0;
            int totalUnqualified = 0;
            foreach (var SM in list_SM)
            {
                totalPlace += SM.PCBCount;
                totalUnqualified += SM.ErrorPcbCount;
            }
            int TotalNumber = totalPlace - totalUnqualified;
            return ((double)TotalNumber / (double)totalPlace).ToString("P2");
        }

        private string ATE_QualiFied(List<ATE_ProductionRecords> list_ATE)
        {
            int Fail = 0;
            int Pass = 0;
            foreach (var ATE in list_ATE)
            {
                Fail += ATE.Fail;
            }
            foreach (var ATE in list_ATE)
            {
                Pass += ATE.Pass;
            }
            int total = Fail + Pass;
            return ((double)Pass / (double)total).ToString("P2");
        }

        private string AOI_QualiFied(List<SMTAOI_ProductionRecords> list_SMTAOI)
        {
            int Fail = 0;
            int Pass = 0;
            foreach (var SMTAOI in list_SMTAOI)
            {
                Pass += SMTAOI.NumberComponents;
            }
           
            foreach (var SMTAOI in list_SMTAOI)
            {
                Fail += SMTAOI.NGNumber;
            }
            int total = Pass- Fail;
            return ((double)total / (double)Pass).ToString("P2");
        }
        #endregion

        #endregion

        #region 机台功率使用统计
        private void MachinePowerUsageStatistics()
        {
            Task.Run(() => AI_PowerDataUpload());
            Task.Run(() => ATE_PowerDataUpload());
            Task.Run(() => GKG_PowerDataUpload());
            Task.Run(() => JUKI_PowerDataUpload());
            Task.Run(() => HL_PowerDataUpload());
            Task.Run(() => JT_PowerDataUpload());
            Task.Run(() => SM_PowerDataUpload());
            Task.Run(() => SMTAOI_PowerDataUpload());
            Task.Run(() => TF1_PowerDataUpload());
            Task.Run(() => TF2_PowerDataUpload());
            Task.Run(() => WS_PowerDataUpload());
        }

        private async Task ATE_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from ATE_ProduceRecords WHERE CAST(TestTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<ATE_ProductionRecords> list_ATE = await readWrite.QueryDataAsync<ATE_ProductionRecords>(query);
                    List<string> machineNames = list_ATE.Select(t => t.MachineName).Distinct().ToList();
                    List<double> ATE_Time = ATE_CycleTime(list_ATE, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "ATE测试机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = ATE_Time[i];
                            electricity.Powers = 1;
                            electricity.PowerLevel = ATE_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("ATE测试机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "ATE测试机设备功率使用情况", Errorlog);
                    await Task.Delay(600000);
                    continue;
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> ATE_CycleTime(List<ATE_ProductionRecords> list_ATE, List<string> machineNames)
        {
            List<double> time = new List<double>();
            TimeSpan timeSpan = TimeSpan.FromSeconds(0);
            for (int i = 0; i < machineNames.Count; i++)
            {
                List<ATE_ProductionRecords> ATE = list_ATE.Where(t => t.MachineName == machineNames[i]).ToList();
                timeSpan = TimeSpan.FromSeconds(0);
                foreach (var g in ATE)
                {
                    timeSpan += TimeSpan.Parse(g.RunTime);
                }
                time.Add(timeSpan.TotalHours);
            }
            return time;
        }

        private async Task AI_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from ai_ProduceRecords WHERE CAST(UTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<AI_ProductionRecords> list_AI = await readWrite.QueryDataAsync<AI_ProductionRecords>(query);
                    List<string> machineNames = list_AI.Select(t => t.MachineName).Distinct().ToList();
                    List<double> AI_Time = AI_CycleTime(list_AI, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "AI插件机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = AI_Time[i];
                            electricity.Powers = 0.8;
                            electricity.PowerLevel = AI_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("AI插件机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "ATE测试机设备功率使用情况", Errorlog);
                    await Task.Delay(600000);
                    continue;
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> AI_CycleTime(List<AI_ProductionRecords> list_AI, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<AI_ProductionRecords> list_MachineTime = list_AI.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].UTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].UTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                time.Add(machineTimeSpan.TotalHours);
            }
            return time;
        }

        private async Task GKG_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from gkg_ProduceRecords WHERE CAST(TimeStamp AS DATE)=CAST(GETDATE() AS DATE)";
                    List<GKG_ProductionRecords> list_gkg = await readWrite.QueryDataAsync<GKG_ProductionRecords>(query);
                    List<string> machineNames = list_gkg.Select(t => t.MachineName).Distinct().ToList();
                    List<double> gkg_Time = GKG_CycleTime(list_gkg, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "GKG印刷机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = gkg_Time[i];
                            electricity.Powers = 2.2;
                            electricity.PowerLevel = gkg_Time[i] * electricity.Powers;
                            electricity.UpdateTime =  DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("GKG印刷机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "gkg设备功率使用情况", Errorlog);
                    await Task.Delay(600000);
                    continue;
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> GKG_CycleTime(List<GKG_ProductionRecords> list_gkg, List<string> machineNames)
        {
            List<double> time = new List<double>();
            TimeSpan timeSpan = TimeSpan.FromSeconds(0);
            for (int i = 0; i < machineNames.Count; i++)
            {
                List<GKG_ProductionRecords> gkg = list_gkg.Where(t => t.MachineName == machineNames[i]).ToList();
                timeSpan = TimeSpan.FromSeconds(0);
                foreach (var g in gkg)
                {
                    timeSpan += TimeSpan.FromSeconds(int.Parse(g.CycleTime));
                }
                time.Add(timeSpan.TotalHours);
            }
            return time;
        }

        private async Task JUKI_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from juki_ProduceRecords WHERE CAST(StopTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<JUKI_ProductionRecords> list_juki = await readWrite.QueryDataAsync<JUKI_ProductionRecords>(query);
                    List<string> machineNames = list_juki.Select(t => t.MachineName).Distinct().ToList();
                    List<double> juki_Time = JUKI_CycleTime(list_juki, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "juki贴片机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = juki_Time[i];
                            electricity.Powers = 2.2;
                            electricity.PowerLevel = juki_Time[i] * electricity.Powers;
                            electricity.UpdateTime =  DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("juki贴片机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "juki设备功率使用情况", Errorlog);
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> JUKI_CycleTime(List<JUKI_ProductionRecords> juki_Models, List<string> machineNames)
        {
            List<double> time = new List<double>();
            TimeSpan CycleTime = TimeSpan.Parse("0");
            for (int i = 0; i < machineNames.Count; i++)
            {
                List<JUKI_ProductionRecords> juki = juki_Models.Where(t => t.MachineName == machineNames[i]).ToList();
                foreach (var jk in juki)
                {
                    CycleTime += TimeSpan.Parse(jk.RunningTime);
                }
                time.Add(CycleTime.TotalHours);
            }
            return time;
        }

        private async Task HL_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from hl_ProductionRecords WHERE CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<HL_ProductionRecords> list_hl = await readWrite.QueryDataAsync<HL_ProductionRecords>(query);
                    List<string> machineNames = list_hl.Select(t => t.MachineName).Distinct().ToList();
                    List<double> hl_Time = HL_CycleTime(list_hl, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "回流焊接机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = hl_Time[i];
                            electricity.Powers = 64;
                            electricity.PowerLevel = hl_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("回流焊接机 电力使用情况已上传", textBox1);
                }
                catch (Exception ex)
                {
                    FileTool.ErrorRecord(ex.ToString() + "回流焊接机 设备功率使用情况", Errorlog);
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> HL_CycleTime(List<HL_ProductionRecords> hl_Models, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<HL_ProductionRecords> list_MachineTime = hl_Models.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    if (list_MachineTime[i].Machine == "冷却模式") continue;
                    machineTimeSpan += currentTime - previousTime;
                }
                time.Add(machineTimeSpan.TotalHours);
            }
            return time;
        }

        private async Task JT_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from jt_ProduceRecords WHERE CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<JT_ProductionRecords> list_JT = await readWrite.QueryDataAsync<JT_ProductionRecords>(query);
                    List<string> machineNames = list_JT.Select(t => t.MachineName).Distinct().ToList();
                    List<double> JT_Time = JT_CycleTime(list_JT, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "JT波峰焊";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = JT_Time[i];
                            electricity.Powers = 3.7;
                            electricity.PowerLevel = JT_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("JT波峰焊机 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> JT_CycleTime(List<JT_ProductionRecords> hl_Models, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<JT_ProductionRecords> list_MachineTime = hl_Models.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                if (machineTimeSpan.TotalHours<0)
                {
                    time.Add(0);
                }
                else
                {
                    time.Add(machineTimeSpan.TotalHours);
                }
            }
            return time;
        }

        private async Task SM_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from sm_ProduceRecords WHERE CAST(Utime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<SM_ProductionRecords> list_SM = await readWrite.QueryDataAsync<SM_ProductionRecords>(query);
                    List<string> machineNames = list_SM.Select(t => t.MachineName).Distinct().ToList();
                    List<double> SM_Time = SM_CycleTime(list_SM, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "三星贴片机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = SM_Time[i];
                            electricity.Powers = 100;
                            electricity.PowerLevel = SM_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("三星贴片机 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> SM_CycleTime(List<SM_ProductionRecords> list_SM, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<SM_ProductionRecords> list_MachineTime = list_SM.Where(t => t.MachineName == Machine).ToList();
                int logTime = 0;
                foreach (var MachineTime in list_MachineTime)
                {
                    logTime = MachineTime.RunTime + MachineTime.StopTime;
                }
                TimeSpan timeSpan = TimeSpan.FromSeconds(logTime);
                time.Add(timeSpan.TotalHours);
            }
            return time;
        }

        private async Task SMTAOI_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from smtaoi_ProduceRecords WHERE CAST(SerialNumber AS DATE)=CAST(GETDATE() AS DATE)";
                    List<SMTAOI_ProductionRecords> list_SMTAOI = await readWrite.QueryDataAsync<SMTAOI_ProductionRecords>(query);
                    List<string> machineNames = list_SMTAOI.Select(t => t.MachineName).Distinct().ToList();
                    List<double> SMTAOI_Time = SMTAOI_CycleTime(list_SMTAOI, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "SMTAOI检测机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = SMTAOI_Time[i];
                            electricity.Powers = 0.8;
                            electricity.PowerLevel = SMTAOI_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("SMTAOI检测机 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> SMTAOI_CycleTime(List<SMTAOI_ProductionRecords> list_SMTAOI, List<string> machineNames)
        {
            TimeSpan PauseTime = TimeSpan.Parse("00:05:00");
            List<double> time = new List<double>();
            TimeSpan totalTimeSpan = TimeSpan.Zero;
            foreach (var machineName in machineNames)
            {
                List<SMTAOI_ProductionRecords> list_MachineTime = list_SMTAOI.Where(t => t.MachineName == machineName).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].SerialNumber);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].SerialNumber);
                    if (currentTime - previousTime > PauseTime) continue;
                    machineTimeSpan += currentTime - previousTime;
                }
                if (machineTimeSpan.TotalHours<0)
                {
                    time.Add(0);
                }
                else
                {
                    time.Add(machineTimeSpan.TotalHours);
                }
            }
            return time;
        }

        private async Task TF1_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from tf1_ProduceRecords WHERE CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<TF1_ProductionRecords> list_TF1 = await readWrite.QueryDataAsync<TF1_ProductionRecords>(query);
                    List<string> machineNames = list_TF1.Select(t => t.MachineName).Distinct().ToList();
                    List<double> TF1_Time = TF1_CycleTime(list_TF1, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "线A涂覆机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = TF1_Time[i];
                            electricity.Powers = 3;
                            electricity.PowerLevel = TF1_Time[i] * electricity.Powers;
                            electricity.UpdateTime =  DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("线A涂覆机 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> TF1_CycleTime(List<TF1_ProductionRecords> list_TF1, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<TF1_ProductionRecords> list_MachineTime = list_TF1.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                time.Add(machineTimeSpan.TotalHours);
            }
            return time;
        }

        private async Task TF2_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from tf2_ProduceRecords WHERE CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<TF2_ProductionRecords> list_TF2 = await readWrite.QueryDataAsync<TF2_ProductionRecords>(query);
                    List<string> machineNames = list_TF2.Select(t => t.MachineName).Distinct().ToList();
                    List<double> TF2_Time = TF2_CycleTime(list_TF2, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "线B涂覆机";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = TF2_Time[i];
                            electricity.Powers = 1.8;
                            electricity.PowerLevel = TF2_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("线B涂覆机 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> TF2_CycleTime(List<TF2_ProductionRecords> list_TF2, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<TF2_ProductionRecords> list_MachineTime = list_TF2.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                time.Add(machineTimeSpan.TotalHours);
            }
            return time;
        }

        private async Task WS_PowerDataUpload()
        {
            while (true)
            {
                try
                {
                    string query = "select * from ws_ProduceRecords WHERE CAST(logTime AS DATE)=CAST(GETDATE() AS DATE)";
                    List<WS_ProductionRecords> list_WS = await readWrite.QueryDataAsync<WS_ProductionRecords>(query);
                    List<string> machineNames = list_WS.Select(t => t.MachineName).Distinct().ToList();
                    List<double> WS_Time = WS_CycleTime(list_WS, machineNames);
                    for (int i = 0; i < machineNames.Count; i++)
                    {
                        try
                        {
                            Electricity electricity = new Electricity();
                            electricity.MachineName = "日东波峰焊";
                            electricity.Model = machineNames[i];
                            electricity.Runtime = WS_Time[i];
                            electricity.Powers = 3.3;
                            electricity.PowerLevel = WS_Time[i] * electricity.Powers;
                            electricity.UpdateTime = DateTime.Now;
                            await readWrite.InsertDatabase(electricity, "Electricity");
                        }
                        catch (Exception) { continue; }
                    }
                    OperationLog("日东波峰焊 电力使用情况已上传", textBox1);
                }
                catch (Exception)
                {
                    await Task.Delay(600000);
                }
                await Task.Delay(3600000);
            }
        }

        private List<double> WS_CycleTime(List<WS_ProductionRecords> list_WS, List<string> machineNames)
        {
            List<double> time = new List<double>();
            foreach (var Machine in machineNames)
            {
                List<WS_ProductionRecords> list_MachineTime = list_WS.Where(t => t.MachineName == Machine).ToList();
                TimeSpan machineTimeSpan = TimeSpan.Zero;
                for (int i = 1; i < list_MachineTime.Count; i++)
                {
                    DateTime currentTime = DateTime.Parse(list_MachineTime[i].logTime);
                    DateTime previousTime = DateTime.Parse(list_MachineTime[i - 1].logTime);
                    machineTimeSpan += currentTime - previousTime;
                }
                time.Add(machineTimeSpan.TotalHours);
            }
            return time;
        }
        #endregion

        #region   文本清除
        /// <summary>
        /// 文本清除
        /// </summary>
        /// <returns></returns>
        public async Task StartTextBoxCleanupAsync()
        {

            await ExecuteClear();
        }

        private async Task ExecuteClear()
        {
            while (true)
            {
                CleanupTextBoxes();
                await Task.Delay(10000);
            }
        }

        private void CleanupTextBoxes()
        {
            CleanupTextBox(textBox1);
            CleanupTextBox(textBox2);
        }

        private void CleanupTextBox(TextBox textBox)
        {
            if (textBox.Lines.Length < 1000) return;
            textBox.Clear();
        }
        #endregion

        private void OperationLog(string content, TextBox text)
        {
            Invoke(new EventHandler(delegate
            {
                text.AppendText($"{content}   {DateTime.Now.ToString()}\r\n");
                textBox1.SelectionStart = textBox1.Text.Length;
            }));
        }

        #region   判断程序是否在运行
        private static string _processName = "BK_SMT Collection";//
        private static string _processName2 = "BK_PluginWorkshop";
        private static string _programPath = @"C:\Users\Administrator\Desktop\数据采集\BK_SMT Collection.exe";
        private static string _programPath2 = @"C:\Users\Administrator\Desktop\插件车间数据采集\BK_PluginWorkshop.exe";
        private static int _checkInterval = 5000;
        private void Monitor()
        {
            while (true)
            {
                try
                {
                    // 检查程序是否在运行
                    bool isRunning = IsProcessRunning(_processName);
                    bool isRunning2 = IsProcessRunning(_processName2);
                    if (!isRunning)
                    {
                        StartProcess(_programPath);
                    }
                    if (!isRunning2)
                    {
                        StartProcess(_programPath2);
                    }
                }
                catch (Exception)
                {
                    Thread.Sleep(_checkInterval);
                    continue;
                }
                Thread.Sleep(_checkInterval);
            }
        }

        private static bool IsProcessRunning(string processName)
        {
            // 获取所有正在运行的进程
            Process[] processes = Process.GetProcessesByName(processName);

            // 如果存在至少一个进程，则返回true
            return processes.Length > 0;
        }

        private static bool StartProcess(string path)
        {
            try
            {
                // 启动进程
                Process.Start(path);
                return true;
            }
            catch (Exception )
            {
                return false;
            }
        }
        #endregion

        public int GetMachineNumber(string Name)
        {
            int Number = 0;
            switch (Name)
            {
                case "GKG自动印刷机":
                    return Number = 2;
                case "回流焊接机":
                    return Number = 3;
                case "AI插件机":
                    return Number = 5;
                case "JUKI贴片机":
                    return Number = 5;
                case "AOI检测机":
                    return Number = 3;
                case "三星贴片机":
                    return Number = 2;
                case "老化测试":
                    return Number = 48;
                case "ATE测试机":
                    return Number = 26;
                case "涂覆机":
                    return Number = 2;
                case "DR波峰焊":
                    return Number = 4;
                case "JT波峰焊":
                    return Number = 2;
                default:
                    return Number;
            }
        }
    }

    public class ResponseData
    {
        public int code { get; set; }
        public string msg { get; set; }
        public Dictionary<string, double> data { get; set; }
        public bool success { get; set; }
    }


}
